php容器类:为什么大家都使用更复杂的方法?
当我查找 php 脚本或查看 php 框架时,我会看到“注册表类”或“容器类”,它们通常使用 __get 魔术方法保存变量或其他对象。
下面是一个过于简单化的示例来说明我的意思:
示例 1:
class container {
private $objects;
public function __get($class){
if(isset($this->objects[$class])){
return $this->objects[$class];
}
return $this->objects[$class] = new $class();
}
}
上面的示例在创建类时将具有更多函数,而不仅仅是调用它,但对于我的示例来说,它应该足够了。 “示例 1”是我在从互联网下载的脚本中主要看到的方式,它维护一个类实例,现在我想知道这个示例不会做同样的事情并且更高效:
示例2:
class simplecontainer {
public function __get($class){
return $this->$class = new $class();
}
}
但我从未在其他人的脚本中看到“示例2”,这让我在考虑使用它之前三思而后行。
我使用几个类来测试容器与简单容器,它们将包含并重复使用大约 100000 次,“示例 1”在我的本地计算机上用了 0.75 秒,“示例 2”用了 0.29 秒。
我应该在我的脚本中使用哪个?示例 1 还是示例 2?为什么?
When I find scripts for php or look at php frameworks I see a "registry class" or a "container class" which often holds variables or other objects utilizing the __get magic method.
Here is a oversimplified example of what I mean:
example 1:
class container {
private $objects;
public function __get($class){
if(isset($this->objects[$class])){
return $this->objects[$class];
}
return $this->objects[$class] = new $class();
}
}
the above example will have more functions to it when creating the class instead of just calling it but for my example it should be enough.
"example 1" is how I mostly see it in scripts downloaded from the internet, it maintains a single class instance, now what I'm wondering is that wouldn't this example do the same thing and be more efficient:
example 2:
class simplecontainer {
public function __get($class){
return $this->$class = new $class();
}
}
But I never see "example 2" in other peoples scripts which makes me think twice before even considering to use it.
I tested container vs simplecontainer using several classes that they would contain and re-use around 100000 times and "example 1" does it in 0.75seconds on my local machine, and "example 2" does it in 0.29seconds.
which should I use in my scripts? example 1 or example 2? and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为在你的版本中我不能这样做:
你的版本依赖于没有与容器对象的私有成员相同的类名。好的,所以应该很容易避免,但追踪错误会很痛苦。安全编码意味着更少的压力。
Because in yours I can't do this:
Your version relies on no class name being the same as a private member of the container object. Ok, so it should be simple to avoid, but would be a pain tracking down a bug for. Safe coding means less stress.
如果没有首先,example2 不会将对象定义为
protected
或private
,这意味着simplecontainer::objects
将是一个可以被覆盖的公共成员,例如:$container->className = new SomethingElse();
Without first off example2 doesnt define the objects as
protected
orprivate
which means thatsimplecontainer::objects
will be a public member that can be overwritten like:$container->className = new SomethingElse();