简体   繁体   English

如何创建一个动态扩展类的工厂,以便其类型发生变化,但它继承父方法?

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

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 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. 我认为在我的工厂函数中,我需要以某种方式声明$ name的值扩展了父类,但未对其进行任何更改,然后构造了一个新的$ 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. 检查一下PHP反射API,那里有您需要提取和构建新类所需的方法,但是不确定如何做然后创建它的实例。 I do know its possible though because im pretty sure this is how Mocking works in PHPUnit. 我确实知道这是可能的,因为我非常确定这是PHPUnit中Mocking的工作方式。 You might also want to look at the various Mock object related classes in PHPUnit to get some ideas as well. 您可能还希望查看PHPUnit中与Mock对象相关的各种类,以获取一些想法。

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? 这里的目标是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM