Domanda

I have an existent class and I want to create a system to load "plugins" for it. Those "plugins" are created as files and then included in the file with the main class.

Now I think the main class needs to extend those little "plugins" with their own classes. The problem is that I don't know what plugins will include different users. So the extending of the classes is dynamically.

How can I extend on-the-fly a class, maybe without using eval (I didn't tested that either)?

È stato utile?

Soluzione

Are you talking about __autoload?

function __autoload($class) {
    require_once($class.'.php');
}
$object = new Something();

This will try to require_once(Something.php);

Altri suggerimenti

You can sort of do it by using PHP's magic functions. Suppose you have class A. You want an "instance" of A with some extra methods available.

class A {
    public $publicA;

    public function doA() {
        $this->publicA = "Apple";
    }
}

class B {
    public $publicB;

    public function doB() {
        $this->publicB = "Bingo";
    }

    private $object;

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

    public function __call($name, $arguments) {
        return call_user_func_array(array($this->object, $name), $arguments);
    }

    public function __get($name) {
        return $this->object->$name;
    }

    public function __set($name, $value) {
        $this->object->$name = $value;
    }
}

$b = new B(new A);

$b->doA();
$b->doB();
echo "$b->publicA, $b->publicB";

The instance $b has the methods and properties of both A and B. This technique can be extended to aggregate functionalities from any number of classes.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top