Jump to content

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/164821-oop-in-php/
Share on other sites

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.

Link to comment
https://forums.phpfreaks.com/topic/164821-oop-in-php/#findComment-869134
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/164821-oop-in-php/#findComment-869139
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.