ilyatau Posted July 5, 2009 Share Posted July 5, 2009 Hello all, I have one small problem with oop in php. I have 2 classes for example point, circle. and I need build class shape. and if I write $shape = new shape; may be with some parametrs. and after, $shape it's not shape object, it's point or circle object, depend of parametrs or global information. Thank you. Quote Link to comment https://forums.phpfreaks.com/topic/164821-oop-in-php/ Share on other sites More sharing options...
Daniel0 Posted July 5, 2009 Share Posted July 5, 2009 Then wait with the instantiation until you know which one it is, or maybe create a factory. Quote Link to comment https://forums.phpfreaks.com/topic/164821-oop-in-php/#findComment-869125 Share on other sites More sharing options...
haku Posted July 5, 2009 Share Posted July 5, 2009 class shape { var $the_shape; function __construct($type) { switch($type) { case 'circle': $this->the_shape = new circle(); break; case 'star': $this->the_shape = new star(); break; } } } class circle() { // class stuff } class star() { // class stuff } There may be some typos - I just threw it out there. Quote Link to comment https://forums.phpfreaks.com/topic/164821-oop-in-php/#findComment-869134 Share on other sites More sharing options...
Daniel0 Posted July 5, 2009 Share Posted July 5, 2009 Rather like this: abstract class Shape { static public function getShape($type) { if (!class_exists($type) || !is_subclass_of($type, __CLASS__)) { throw new InvalidArgumentException('Type must be a valid shape.'); } return new $type; } } class Point extends Shape {} class Circle extends Shape {} var_dump(Shape::getShape('Point')); var_dump(Shape::getShape('Circle')); var_dump(Shape::getShape('foo')); Quote Link to comment https://forums.phpfreaks.com/topic/164821-oop-in-php/#findComment-869139 Share on other sites More sharing options...
ilyatau Posted July 5, 2009 Author Share Posted July 5, 2009 Thank you, very much Quote Link to comment https://forums.phpfreaks.com/topic/164821-oop-in-php/#findComment-869150 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.