PHP: using $ this in the constructor

I have an idea to use this syntax in php. This illustrates that there are various ways to return an object.

function __construct() { if(some_case()) $this = method1(); else $this = method2(); } 

A nightmare? Or does it work?

+4
source share
7 answers

Or does it work?

This does not work. You cannot undo or radically change the object that is created in the constructor. You also cannot set the return value. All you can do is set the properties of the object.

One way around this is to have a separate class or factory function that checks the condition and returns a new instance of the correct object as follows:

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

See also:

+13
source

Why not do something more general, for example:

 function __construct() { if(some_case()) $this->construct1(); else $this->construct2(); } 
+4
source

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

 function __construct() { if(some_case()) $this->method1(); else $this->method2(); } 
+1
source

It sounds a bit like a Singleton class template .

+1
source

You can make a 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 ();
+1
source

See @Ivan's answer among others for the correct syntax of what it looks like, as you are trying to do.

However, there is another alternative - use the 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 cannot use $this in a static method)

0
source

If you want to share some features, do some of them.

 class base{ 'your class' } class A extends base{ 'your class' } class B extends base{ 'your class' } 

And call

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

Source: https://habr.com/ru/post/1340342/


All Articles