5

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 Answers 7

14

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Should be a static method though.
4

Why not to do something more common like:

function __construct() {

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

Comments

1

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

function __construct() {

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

}

Comments

1

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

Comments

1

It sounds a little bit like the Singleton class pattern.

Comments

0

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)

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.