PHP: using $this in constructor

6.9k views Asked by At

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?

7

There are 7 answers

1
Pekka On BEST ANSWER

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:

0
Ivan On

Why not to do something more common like:

function __construct() {

   if(some_case())
      $this->construct1();
   else
      $this->construct2();
}
0
Foo Bah On

You can just create class methods method1 and method2 and just write

function __construct() {

   if(some_case())
      $this->method1();
   else
      $this->method2();

}
0
powtac On

It sounds a little bit like the Singleton class pattern.

0
Matej Baćo On

You can make factory method.

Example:

class A {}
class B {}

class C {
   function static getObject() {
      if(some_case())
         return new A();
      else
          return new B();
   }
}

$ob = C::getObject();
0
Spudley On

See @Ivan's reply among others for the correct syntax for what it looks like you're trying to do.

However, there are is another alternative - use a static method as an alternative constructor:

class myclass {
     function __construct() { /* normal setup stuff here */}

     public static function AlternativeConstructor() {
         $obj = new myclass; //this will run the normal __construct() code
         $obj->somevar = 54; //special case in this constructor.
         return $obj;
     }

}

...

//this is how you would use the alternative constructor.
$myobject = myclass::AlternativeConstructor();

(note: you definitely can't use $this in a static method)

0
user1661197 On

If you want to share some functions, do some like

class base{
    'your class'
}

class A extends base{
    'your class'
}

class B extends base{
    'your class'
}

And call like

if(some_case())
    $obj = new A();
else
    $obj = new B();