![](/img/trans.png)
[英]How can I create a child class which only inherits the methods but not the properties of the parent?
[英]How do you create a factory that dynamically extends a class so its type changes but it inherits parent methods?
我想做的是有一个静态工厂函数,可以提供一系列属性,它返回一个对象,该对象属于先前未声明的类,该类扩展了已知的类。
基本上:
<?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
}
这样,如果我编写代码:
<?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";
}
我得到: [编辑]
bar Object
(
[a] => 17
)
is a Foo
moo Object
(
[a] => 5
)
is a Foo
但是我不知道从哪里开始寻找执行此操作所需的命令。 我认为在我的工厂函数中,我需要以某种方式声明$ name的值扩展了父类,但未对其进行任何更改,然后构造了一个新的$ name。 这样,它就具有父类的所有功能,只是类型不同。
检查一下PHP反射API,那里有您需要提取和构建新类所需的方法,但是不确定如何做然后创建它的实例。 我确实知道这是可能的,因为我非常确定这是PHPUnit中Mocking的工作方式。 您可能还希望查看PHPUnit中与Mock对象相关的各种类,以获取一些想法。
也就是说,除非您实际上要添加/重载方法,否则为什么还要这样做呢? 为什么不只在对象中使用属性或使用接口? 这里的目标是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.