PHP:类属性违背我的意愿链接
我都快疯了。我已经把我的课程解构到了最基本的层面,而且它还在发生。 所以这个班:PHP:类属性违背我的意愿链接,php,Php,我都快疯了。我已经把我的课程解构到了最基本的层面,而且它还在发生。 所以这个班: class Insanity { protected $simon; protected $garfunkel; public function __construct() { $this->simon = new stdClass(); $this->garfunkel = new stdClass(); } } 一切都很好,
class Insanity
{
protected $simon;
protected $garfunkel;
public function __construct()
{
$this->simon = new stdClass();
$this->garfunkel = new stdClass();
}
}
一切都很好,很漂亮。如果我做了
$this->simon->name='paul'代码>和$this->garfunkel->name='art'他们俩都是快乐的分居者
直到我做了$this->simon=$this->garfunkel代码>
从这一点开始,它们就成为链接/引用或其他任何东西,
所以当我做$simon->name='homer'代码>,它将成为两者的名称
即使我做了$this->simon->whatTheF='uck'
然后$garfunkel
也以该属性结束,尽管快速var\u dump()
声明这两个变量仍然是分开的(按名称)
有人知道为什么吗?$simon
和$garfunkel
不包含对象本身。它们只是对对象的引用。你也可以叫它们指针。如果执行$simon=$garfunkel
,则只需复制此引用,因此$simon
将指向与$garfunkel
完全相同的对象
如果要复制对象本身,PHP会为您提供clone
关键字:
$simon = clone $garfunkel;
你是说$this->simon=stdClass()代码>?等等?您能否提供有关stdClass函数的信息?还是应该是新stdClass
?是的,对不起,语法非常错误。修正了。我完全喜欢你给你的东西命名的方式;)好啊就这样。我从来不知道。我可以发誓,我过去做过类似的事情,没有任何问题(也就是说,我当时没有意识到……谁知道我破坏了什么……谢谢你注意,这只适用于对象。默认情况下,其他类型不显示此行为。但是,如果你明确地说,你也可以参考其他类型<代码>$foo=&$bar
将使$foo
包含对$bar
包含的任何内容的引用。有关更多信息,请参阅。