Jump to content

OOP in php


ilyatau

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.