我最近一直在处理一些旧的项目,并对它们进行了一些升级。我已经构造了类似于以下代码的代码:
class Foo{
public $some_variable = "AAA";
public function do_some_action(){
echo $this->some_variable;
// Prints out 'AAA'
$bar = new Bar($this);
$bar->different_action();
echo $this->some_variable;
// Prints out 'BBB' - why ?
}
} class Bar {
//Constructor
public function Bar($foo){
$this->foo = $foo;
}
public function different_action(){
$this->foo->some_variable = "BBB";
}
}
我不太明白为什么函数Bar::different_action()会影响Foo的公共变量。在这种情况下,>>$this<<总是作为引用传递吗?我希望有一些参考,比如:
public function Bar(&$foo){
$this->foo =& $foo;
}
我的逻辑肯定失败,但如果有人告诉我地点和原因,我会很感激:)
发布于 2014-07-17 12:56:27
对象通过引用传递: Docs:http://php.net/manual/en/language.oop5.references.php
发布于 2014-07-18 09:25:05
Bar
的构造函数参数没有&
,因此它是由值传递的。
传递值意味着函数获得值的一个单独副本,并且分配给被调用函数中的参数(在本例中,是构造函数中的$foo = something
)不影响调用者。但是,由于本例中的值是一个对象指针,所以您可以使用它来调用更改对象状态的指向对象的方法。
如果您知道C++,下面是与C++中的代码等价的内容,保留代码和每一行的结构,并按C++中的要求添加类型:
class Foo{
public:
string some_variable = "AAA";
void do_some_action(){
cout << this->some_variable;
// Prints out 'AAA'
Bar *bar = new Bar(this);
bar->different_action();
cout << this->some_variable;
// Prints out 'BBB' - why ?
}
} class Bar {
Foo *foo;
public:
//Constructor
Bar(Foo *foo){
this->foo = foo;
}
void different_action(){
this->foo->some_variable = "BBB";
}
}
在这个C++代码中,不存在引用传递。(只有当参数具有&
时,它才会在C++中通过引用传递,就像在PHP中一样。)你能看到为什么要改变对象吗?
通过引用传递对象指针,就像您在上一个代码示例中所做的那样,只有当您希望将对象指针赋值给参数时才会有用,从而更改调用范围中的对象指针变量(但是$this
无论如何都是不可分配的,因此在这种情况下没有意义)。
发布于 2014-07-17 12:59:34
在PHP中,所有对象都通过引用传递。要通过引用传递的所有其他变量都需要在函数/方法参数前面加上一个符号(&
--引用操作符)。
function some_action(&$variable) {
$variable = 'new value';
}
$variable = 'string';
some_action($variable); // $variable now has a new value. Passing objects to this function will always pass them by reference - automatically.
https://stackoverflow.com/questions/24804127
复制相似问题