开发者

How do you create a factory that dynamically extends a class so its type changes but it inherits parent methods?

开发者 https://www.devze.com 2022-12-18 23:52 出处:网络
What I would like to do is have a static factory function that you can give a series of attributes and it returns an object that is of a previously undeclared class that extends a known class.

What I would like to do is have a static factory function that you can give a series of attributes and it returns an object that is of a previously undeclared class that extends a known class.

Basically:

<?php
class foo {
  public $a;

  function increment($b = 1){
    $this->a += $b;
  }
}

function factory($name, $a){
  //returns an object of class $name that ex开发者_运维技巧tends foo with $this->a set to $a
}

so that if I write the code:

<?php
$bar = factory("bar",12);
$bar->increment(5);
print_r($bar);
if(is_a($bar, "foo")){
  echo "is a Foo";
}
$moo = factory("moo", 4);
$moo->increment();
print_r($moo);
if(is_a($moo, "foo")){
  echo "is a Foo";
}

I get: [edit]

bar Object
(
    [a] => 17
)
is a Foo
moo Object
(
    [a] => 5
)
is a Foo

But I don't know where to start looking for the commands necessary to do this. I think that in my factory function I need to somehow declare that the value of $name extends parent class but makes no changes to it, then constructs a new $name. That way it has all the functionality of the parent class, just a different type.


Check out the PHP reflection API has the methods you need to extract and build the new class there but, how to go about doing it and then creating an instance of it im not sure of. I do know its possible though because im pretty sure this is how Mocking works in PHPUnit. You might also want to look at the various Mock object related classes in PHPUnit to get some ideas as well.

That said unless you are actually adding/overloading methods, why would you even want to do this? Why not just use a property in the object or use a an interface? Whats the goal here?

0

精彩评论

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