Search code examples
phpconstruct

PHP: using $this in constructor


I have an idea of using this syntax in php. It illustrates that there are different fallback ways to create an object

function __construct() {

   if(some_case())
      $this = method1();
   else
      $this = method2();

}

Is this a nightmare? Or it works?


Solution

  • Or it works?

    It doesn't work. You can't unset or fundamentally alter the object that is being created in the constructor. You can also not set a return value. All you can do is set the object's properties.

    One way to get around this is having a separate "factory" class or function, that checks the condition and returns a new instance of the correct object like so:

    function factory() {
    
       if(some_case())
          return new class1();
      else
          return new class2();
    
    }
    

    See also: