开发者

PHP: using $this in constructor

I have an idea of using this syntax in php. It illustrates that there are different fallback wa开发者_如何学JAVAys to create an object

function __construct() {

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

}

Is this a nightmare? Or it works?


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


Why not to do something more common like:

function __construct() {

   if(some_case())
      $this->construct1();
   else
      $this->construct2();
}


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

function __construct() {

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

}


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();


It sounds a little bit like the Singleton class pattern.


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)


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜