php - 如何动态地将方法添加到类中?
问题描述
我知道我可以在运行时向 PHP 类动态添加属性(参见下面的示例)。
但是我找不到在运行时向类添加方法的方法。
到目前为止我已经尝试过:
class Test {
public $name;
public function __construct($name){
$this->name=$name;
}
public function addProperty($name,$value){
$this->$name=$value;
}
public function addMethod($name, $value) {
$this->$name=$value;
}
}
$t=new Test("Morris");
echo $t->name .'<br>'; // => "Morris"
echo $t->firstname .'<br>'; // as expected => "Notice: Undefined property: Test::$firstname"
$t->addProperty("firstname","John"); // dynamically add new property
echo $t->firstname .'<br>'; // => "John" (property has definitely been added).
$f=function($i){return $i*$i;};
echo $f(7); // ==> 49
$t->addMethod("square",$f); // trying to dynamically add a new method
echo $t->square(4); // expected: 46, but..... => "Fatal error: Call to undefined method Test::square()"
这行不通。
还有什么我应该做的addMethod()
吗?
或者一些应该被覆盖的魔法类方法?
有可能吗?
解决方案
请找到以下代码
class Foo
{
public function __call($method, $args)
{
if (isset($this->$method)) {
$func = $this->$method;
return call_user_func_array($func, $args);
}
}
}
$foo = new Foo();
$foo->bar = function () { echo "Hello, this function is added at runtime"; };
$foo->bar();
推荐阅读
- javascript - 按钮在模拟器上工作但不在物理设备上
- sql - 根据 _Viewstart 文件中的 SQL 查询选择布局文件
- docker - 如何更改 docker 仪表板中的容器设置?
- javascript - 访问表标题行键反应
- python - AsyncIO - 如何测试我的函数是否阻塞?
- php - Laravel 7 护照 API 验证
- composer-php - 我可以将 TYPO3 安装的更新模式从作曲家更改为自动吗?
- docker - 在 Nginx 容器 wsl2 上运行 Laravel 时,Docker 非常慢
- javascript - 模拟一个按钮的点击,正常的方法不起作用
- python - 从 Python 中的子类实例获取父类的 __dict__ 表示