构造函数中的 PHP 动态方法


PHP dynamic methods in constructor

我希望能够在__construct中创建方法

我尝试通过以下方式使用 lambda

// This is what I am trying to achieve as an end result
class A extends Z{
    public function __construct() {
        parent::__construct()
    }
    public function myfunc() { // do something }
}

// This was an attempt to implement it
class A extends Z{
    public function __construct() {
        //example
        if ($something_is_true) {
            $this->myfunc = function () {}
        }
        parent::__construct()
    }
}

我希望这能解释我想要实现的目标

编辑

我有映射到函数的 URL,并且我想有一些逻辑来确定类上存在哪些 URL 映射函数

不要认为这是不可能的。但是在类中动态"创建"方法的另一种方法是使用魔术__call()方法。

实现此方法后,任何在对象上调用不存在的方法的尝试都将改为调用 __call() 方法。传入的第一个参数将是用户调用的函数的名称,第二个参数将是参数。

有关更多详细信息,请参阅手册。

一旦定义了类,就不能使用标准 PHP 向其添加新方法。我建议也使用 __call,但如果您同意使用变量,您也可以通过使用 create_function 动态创建函数内容来完成您想要的:

<?php
class A
{
    public function __construct()
    {
        $this->addUpEchoAndReturn=create_function('$a,$b','$c=$a+$b;echo "$a+$b=$c<hr />";return $c;');
    }
    public function add_up_and_echo($a,$b,$c,$d)
    {
        $fn=$this->addUpEchoAndReturn;
        return $fn($fn($a, $b),$fn($c, $d));
    }
}

$x=new A();
$result=$x->add_up_and_echo(3,4,5,25);
echo "<hr /><hr />Final Result: $result";
?>