tags:

views:

50

answers:

1

Suppose we have a class. We create an object from the class and when we do the class Extends himself base on the object initialization value..

For example:

$objectType1 = new Types(1);
$objectType1->Activate(); // It calls an activation function for type 1

$objectType2 = new Types(2);
$objectType2->Activate(); // It calls an activation function for type 2

I don't want to use the standard procedure of class extending:

class type1 extends types{}
+3  A: 

You cannot extend a class at runtime. Use an instance variable to distinct the two type or use a factory.

Example for instance variable:

class Types() {
    private $type;

    public function __construct($type) {
        $this->type = $type;
    }

    public function activate() {
        if($this->$type == 1) {
             // do this
        }
        else if($this->type == 2) {
             // do that
        }
   }
}

Example for factory pattern:

abstract class BaseClass {
    // Force Extending class to define this method
    abstract public function activate();

    // Common method
    public function printOut() {
        echo "Hello World";
    }
}

class Type1 extends BaseClass {

    public function activate() {
       // do something
    }
}

class Type2 extends BaseClass {

    public function activate() {
        // do something else
    }
}

class TypeFactory {

    public static function getType($tpye) {
        if($type == 1) {
            return new Type1();
        }
        else if($type == 2) {
            return new Type2();
        }
    }
}

then you do:

$obj = TypeFactory::getType($1);
$obj->activate();

Update:

Since PHP 5.3 you can use anonymous functions. Maybe you can make use of this.

Felix Kling
Whith a capital letter at Activate and === instead of == and it would be perfect.PS : an else {} would be great too
xavierm02
it's not overriding but ty
EBAGHAKI
@Xavier: This is just a rough sketch and should demonstrate the general approach. Method names starting with capital letters are ugly :)
Felix Kling
You're right but you should've told him that names starting with capital letter are reserved for Classes in order to make the code easier to read.
xavierm02