是否可以在 PHP 中动态扩展类对象?这样做最优雅的方式是什么?
一些示例代码用于进一步解释:
class BasicClass {
private $variable;
public function BasicFunction() {
// do something
$this->variable = 10;
}
}
class ExtendedClass extends BasicClass {
public function ExtendedFunction() {
// do something else with basic class variable
return $this->variable/2;
}
}
$A = new BasicClass();
If(condition for extension){
// A should be of class ExtendedClass
// and the current class variables should be kept
// ... insert the magic code here ...
// afterwards we would be able to use the ExtendedFunction with the original variables of the object
$A->ExtendedFunction();
}
解决此问题的一种方法是创建 ExtendedClass 的新对象并从旧对象复制所有变量。但这可以更优雅地完成吗?