class substitution in php -
is there way make work? see example :
class car { function __construct($type){ switch ($type) { case 'big' : return new big_car(); case 'small' : return new small_car(); } } function whatisit () { echo "this car ;( \n"; } } class big_car extends car { function __construct(){} function whatisit () { echo "this big car ;) \n"; } } class small_car extends car { function __construct(){} function whatisit () { echo "this small car ;) \n"; } }
so goal use way:
$mycar = new car('big'); $mycar->whatisit(); // want it's big
i guess bad way , cannot work way maybe there trick?
ps:: know can use special static method but...
you need car factory create new cars; not javascript :)
class car_factory { function create_car($type = null) { switch ($type) { case 'big': return new big_car(); case 'small': return new small_car(); case null: return new car(); } throw new invalidargumentexception($type); } } $factory = new car_factory; $small_car = $factory->create_car('small'); $std_car = $factory->create_car();
of course, should remove __construct
function original code.
as mentioned in comments generalize using dynamic classes, assuming class extensions have same constructor , class naming consistent:
class car_factory { function create_car($type = null) { if (is_null($type)) { return new car(); } $class = "{$type}_car"; if (class_exists($class)) { $obj = new $class(); if ($obj instanceof car) { return $obj; } } throw new invalidargumentexception($type); } }
personally have no preferences either way; if extensibility key factor, go it, otherwise stick simple switch
.
Comments
Post a Comment