隧道两个或多个对象
我有两个独立的对象,一个主对象和一个“子对象”。它实际上不是一个真正的子对象,因为我通过构造函数将整个父对象添加到子对象中。
像这样:
class core
{
public function __get($class)
{
$this->load($class);
}
public function load($class, $file = null, $lib = true)
{
if($file == null)
$file = $class;
if($lib == true)
include(LIBPATH.$file.PHP);
else
include(SYSPATH.$file.PHP);
$this->$class = new $class($this);
}
}
而“孩子”:
class Child implements myStruct
{
public function __construct($obj)
{
$this->obj =& $obj;
}
}
这是否像我想象的那么丑陋,或者这个解决方案可以接受吗?
I have two separate objects, a main and a "child". Its physically not a real child object, because I add the whole parent through the constructor to the child.
Like this:
class core
{
public function __get($class)
{
$this->load($class);
}
public function load($class, $file = null, $lib = true)
{
if($file == null)
$file = $class;
if($lib == true)
include(LIBPATH.$file.PHP);
else
include(SYSPATH.$file.PHP);
$this->$class = new $class($this);
}
}
And the "child":
class Child implements myStruct
{
public function __construct($obj)
{
$this->obj =& $obj;
}
}
Is this as ugly as i think, or is this solution acceptable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这绝对是次优的。第一:
没有这个必要。从 PHP 5 开始,对象在用户空间中通过引用来引用。当你复制一个对象时,你实际上是在复制一个引用。您可以在此处删除引用运算符:
$this->obj = $obj
。查看
spl_autoload
自动加载类。它并不等同于你正在做的事情——你正在使用某种容器来保存对对象的引用(每个类只有一个对象),但我怀疑这就是你想要的。It's definitely suboptimal. First:
There is no need for this. As of PHP 5, objects are refereed to in user space through references. When you copy an object, you're actually copying a reference. You can drop the reference operator here:
$this->obj = $obj
.Look
spl_autoload
for autoloading classes. It's not equivalent to what you're doing -- you're using some kind of container to hold references to objects (and only one object per class), but I suspect it's what you want.