PHP:我可以在_constructor中传递$ this吗?

0 php constructor this

我想将自己的构造函数中的php对象传递给另一个对象,如下所示:

class foo {

 $parent_object;

 public function __construct($obj) {
  $this->parent_object = $obj;
  }
 }

class bar {

 public function __construct() {
  $blub = new foo($this);
  }
 }
Run Code Online (Sandbox Code Playgroud)

我问自己的问题是:我可以在bar的构造函数中传递$ this,因为实际上没有创建对象...所以$ this已经是对整个对象的有效引用了吗?

Hal*_*yon 5

你当然可以.请记住,$this始终指向当前对象.所以在:

$blub = new foo($this);
Run Code Online (Sandbox Code Playgroud)

$this指向实例bar.所以$obj在构造函数中foo就是那个实例bar.

$this在构造函数的开头可用.现在,如果bar立即调用函数,$obj则可能是实例bar尚未处于正确状态(即$blub尚未分配).这可能会导致引用问题,解决方法是将引用交换移出构造函数.