【问题标题】:Exact difference between self::__construct() and new self()self::__construct() 和 new self() 之间的确切区别
【发布时间】:2012-04-04 15:35:47
【问题描述】:

你能告诉我return self::__construct()return new self()之间的确切区别吗?

似乎可以在创建对象时从__construct() 调用中返回self::__construct(),返回对象本身,就好像第一个__construct() 从未被调用过一样。

【问题讨论】:

  • 确切的区别是self::__construct() 会出现致命错误,因为构造函数被暗示为静态的——php 没有(至少不是我的 5.3.10采用)。 new self() 将正确创建对象。当然,这在很大程度上也取决于上下文,例如您从哪里调用这些语句。
  • @N.B. No fatal error in 5.2.5... 当你认为你可以合法地做parent::__construct()...
  • @DaveRandom - 我确实说过“这取决于上下文”,不是吗?

标签: php class constructor instance


【解决方案1】:

这在代码中得到了最好的说明:

class MyClass {

   public $arg;

   public function __construct ($arg = NULL) {
     if ($arg !== NULL) $this->arg = $arg;
     return $this->arg;
   }

   public function returnThisConstruct () {
     return $this->__construct();
   }

   public function returnSelfConstruct () {
     return self::__construct();
   }

   public function returnNewSelf () {
     return new self();
   }

}

$obj = new MyClass('Hello!');
var_dump($obj);
/*
  object(MyClass)#1 (1) {
    ["arg"]=>
    string(6) "Hello!"
  }
*/

var_dump($obj->returnThisConstruct());
/*
  string(6) "Hello!"
*/

var_dump($obj->returnNewSelf());
/*
  object(MyClass)#2 (1) {
    ["arg"]=>
    NULL
  }
*/

var_dump($obj->returnSelfConstruct());
/*
  string(6) "Hello!"
*/

return self::__construct() 返回对象__construct 方法返回的。它还会再次运行构造函数中的代码。当从类__construct 方法本身调用时,返回self::__construct() 实际上将返回构造的类本身,就像该方法通常所做的那样。

return new self(); 返回调用对象类的一个新实例

【讨论】:

  • @DaveRandom 我认为一个 php 构造函数应该只返回他创建的对象,而不是一个值。
【解决方案2】:

我相信new self() 会创建一个新的类实例,而self::__construct () 只调用类__construct 方法。

【讨论】:

  • __construct 方法通常没有返回值。
  • @Rocket - __construct 总是有一个返回值——创建的对象。
  • @N.B.不是这样的,is it? Construct 不返回类的实例,它在实例化期间被调用并返回 NULL。至少在实践中。
  • @N.B.:不完全是。在做new class时,忽略__construct的返回值,返回对象。但是,当像普通函数一样调用__construct 时,它就是这样做的。它就像一个函数,并返回它返回的任何内容。 ideone.com/IZSi8
  • __construct 应始终返回 void。是 new 运算符返回类的实例,而不是构造函数。
猜你喜欢
  • 2011-11-18
  • 2014-01-31
  • 1970-01-01
  • 2011-06-04
  • 2011-01-02
  • 2017-08-24
  • 2013-11-15
  • 1970-01-01
相关资源
最近更新 更多