一个简单的例子:
class A
{
/**
* @var Injected
*/
private $injected;
public function __construct(Injected $injected)
{
$this->injected = $injected;
}
public function get()
{
$this->injected->e();
}
}
class B
{
/**
* @var Injected
*/
private $injected;
public function __construct(Injected $injected)
{
$this->injected = $injected;
}
public function get()
{
$this->injected->e();
}
}
class Injected
{
private $a;
public function __construct()
{
$this->a = mt_rand(1,9999999999);
echo 'Generated: '.$this->a.'<br>';
}
public function e()
{
echo $this->a.'<br>';
}
}
$o = new Injected();
$a = new A($o);
$b = new B($o);
$a->get();
$b->get();
$o = new Injected();
$a->get();
$b->get();
当我跑步时:
Generated: 1223710791
1223710791
1223710791
Generated: 1135116298
1223710791
1223710791
这不正是我的预期。前三个1223710791是正确的 - 但最后两个似乎失败了。我想得到这个!
Generated: 1223710791
1223710791
1223710791
Generated: 1135116298
1135116298
1135116298
即使我替换了$o
的引用,它也不会在A
和B
类中更改。为什么?如果它们是正常变量,那将是可以理解的,但它们是对象,所以参考!我甚至没有克隆它们......这样就没有办法改变$injected
,除了setter(这次不是一个选项)
答案 0 :(得分:2)
您可以通过替换A
/ B
类的构造函数来实现(奇怪且可能无法预测)行为:
public function __construct(Injected &$injected)
{
$this->injected = &$injected;
}
答案 1 :(得分:0)
您可以使用PHP的static
功能。你可以说它们的工作方式几乎就像引用一样,我不知道引擎盖下的所有细节,但是下面的内容会按照你的预期工作。
您需要将部分Injected
代码更改为静态代码并保持其他代码不变:
class A
{
/**
* @var Injected
*/
private $injected;
public function __construct(Injected $injected)
{
$this->injected = $injected;
}
public function get()
{
$this->injected->e();
}
}
class B
{
/**
* @var Injected
*/
private $injected;
public function __construct(Injected $injected)
{
$this->injected = $injected;
}
public function get()
{
$this->injected->e();
}
}
class Injected
{
private static $a;
public function __construct()
{
self::$a = mt_rand(1,9999999999);
echo 'Generated: '.self::$a.'<br>';
}
public function e()
{
echo self::$a.'<br>';
}
}
$o = new Injected();
$a = new A($o);
$b = new B($o);
$a->get();
$b->get();
$o = new Injected();
$a->get();
$b->get();
结果:
Generated: 5231916164
5231916164
5231916164
Generated: 166525017
166525017
166525017