Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: using $this in constructor

Tags:

php

construct

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?

like image 983
Dan Avatar asked Dec 01 '22 03:12

Dan


1 Answers

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:

  • Breaking the constructor
  • PHP constructor to return a NULL
like image 65
Pekka Avatar answered Dec 09 '22 10:12

Pekka