1

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)?

Octavian
  • 4,519
  • 8
  • 28
  • 39
  • 1
    You want to dynamically change the parent class? The class your plugin inherits from? This speaks to a pretty serious design flaw. There really is no reason you should have to do this, and no easy way to do it. – user229044 Aug 13 '12 at 22:38
  • 1
    You do something wrong for sure. Your plugin design is broken. Technically you can eval/include dynamic string data, so you can make that happen whatever you like - it is just you're doing it wrong design wise. – hakre Aug 13 '12 at 22:41
  • i'm guessing you're coming to PHPs classical inheritance from some previous javascript prototypical inheritance experience? you might need to read up on classical inheritance. – David Chan Aug 13 '12 at 22:42
  • @Octavian Perhaps you could post a little bit of pseudo-code that represents what you're wanting to do? I'm leaning towards agreeing with the other commenters in saying that you've got a design flaw here... – Matthew Blancarte Aug 13 '12 at 22:56

2 Answers2

0

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.

cleong
  • 7,242
  • 4
  • 31
  • 40
0

Are you talking about __autoload?

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

This will try to require_once(Something.php);

romo
  • 1,990
  • 11
  • 10