The exact difference between self :: __ construct () and the new self ()

Can you tell the exact difference between return self::__construct()and return new self()?

It seems, in fact, you can return self::__construct()from the call __construct()when creating the object, returning the object itself, as if the first one __construct()had not even been called.

+5
source share
2 answers

This is best illustrated by the code:

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()returns the value returned by the method __construct. It also runs the code again in the constructor. When called from the class itself __construct, the return self::__construct()will actually return the constructed class as usual, as usual.

return new self(); returns a new instance of the class of the calling object.

+6

, new self() , self::__construct () __construct.

+5

All Articles