php - Letting an object decide its class -
i'm sorry not come more descriptive title. problem following. assume have 2 classes , b , know may happen code tries instantiate object of type when needed object of type b. point the code decide 1 right object naturally belongs class a , not client code.
in javascript (ok, js doesn't have classes, makes point clear) can do
function a() { if(some_condition) { return new b(); } //else proceed customize , return our object }
i want similar in php. best thing can come is
class { private function __construct() { //whatever need } public static function getinstance() { if(some_condition) { return new b(); } else { return new a(); } } }
the problem client code have know special , have instantiate objects static method.
is there way delegate choice of type of object return in seamless way?
unfortunately no, best think can like:
class decider { public static function decide() { if(some_condition) { return "a"; } else { return "b"; } } } $new_class = decider::decide(); $new_object = $new_class();
but again no different way approached it. wouldnt consider invalid design patter though, leave external class deciding rather have class "a" or class "b" deciding within them. ideally classes should encapsulated in such way not require other classes unless member variables of class or passed class functional purposes.
Comments
Post a Comment