Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact difference between self::__construct() and new self()

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

It seems one can actually return a self::__construct() from a __construct() call when the object is created, returning the object itself as if the first __construct() was never even called.

like image 776
halfpastfour.am Avatar asked Apr 04 '12 15:04

halfpastfour.am


2 Answers

This is best illustrated in 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 objects __construct method. It also runs the code in the constructor again. When called from the classes __construct method itself, returning self::__construct() will actually return the constructed class itself as the the method would normally do.

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

like image 130
DaveRandom Avatar answered Sep 30 '22 18:09

DaveRandom


I believe that new self() would create a new instance of the class while self::__construct ()only calls the classes __construct method.

like image 33
dm03514 Avatar answered Sep 30 '22 18:09

dm03514