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

class, constructor, instance, php

Solution

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.

Problem

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.

Original source