views:

52

answers:

1

What I would like to do is have a static factory function that you give it 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 extends 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.

+1  A: 

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?

prodigitalson