douzi1991 2013-02-19 17:26
浏览 59

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

I would like to pass a php object in its own constructor to another object like this:

class foo {

 $parent_object;

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

class bar {

 public function __construct() {
  $blub = new foo($this);
  }
 }

The question I am asking myself is: Can I pass $this in the constructor of bar, because the object has not actually been created... so is $this already a valid reference to the whole object?

  • 写回答

1条回答 默认 最新

  • doufuxing8691 2013-02-19 17:28
    关注

    Sure you can. Keep in mind that $this always points to the current object though. So in:

    $blub = new foo($this);
    

    $this points to the instance of bar. So $obj in the constructor of foo is that instance of bar.

    $this is available at the beginning of the constructor. Now if bar immediately calls functions on $obj it might be that the instance of bar is not yet in the right state (ie. $blub has not been assigned). This could lead to reference issues, the solution to that would be to move the reference exchange out of the constructor.

    评论

报告相同问题?

悬赏问题

  • ¥15 c++ gmssl sm2验签demo
  • ¥15 关于模的完全剩余系(关键词-数学方法)
  • ¥15 有没有人懂这个博图程序怎么写,还要跟SFB连接,真的不会,求帮助
  • ¥15 关于移动机器人坐标计算
  • ¥30 模拟电路 logisim
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音