开发者

Can a class Extend or Override himself?

开发者 https://www.devze.com 2022-12-26 15:01 出处:网络
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..

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{}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消