如何动态添加方法

Sha*_*ker 18 php class

我正在尝试从外部文件动态添加方法.现在我__call在课堂上有方法所以当我打电话给我想要的方法时,__call包括它给我; 问题是我想通过使用我的类调用加载函数,我不希望在类之外加载函数;

Class myClass
{
    function__call($name, $args)
    {
        require_once($name.".php");
    }
}
Run Code Online (Sandbox Code Playgroud)

echoA.php:

function echoA()
{
    echo("A");
}
Run Code Online (Sandbox Code Playgroud)

然后我想用它像:

$myClass = new myClass();
$myClass->echoA();
Run Code Online (Sandbox Code Playgroud)

任何建议将被认真考虑.

dec*_*eze 13

你不能在运行时,句点动态地向类添加方法.*
PHP根本不是一种非常易于破解的语言.

*没有丑陋的黑客.


Pav*_*ari 8

这是你需要的吗?

$methodOne = function ()
{
    echo "I am  doing one.".PHP_EOL;
};

$methodTwo = function ()
{
    echo "I am doing two.".PHP_EOL;
};

class Composite
{
    function addMethod($name, $method)
    {
        $this->{$name} = $method;
    }

    public function __call($name, $arguments)
    {
        return call_user_func($this->{$name}, $arguments);
    }
}


$one = new Composite();
$one -> addMethod("method1", $methodOne);
$one -> method1();
$one -> addMethod("method2", $methodTwo);
$one -> method2();
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以动态添加属性和方法,前提是通过构造函数完成,就像将一个函数作为另一个函数的参数传递一样。

class Example {
    function __construct($f)
    {
       $this->action=$f;
    }
}

function fun() {
   echo "hello\n";
}

$ex1 = new class('fun');
Run Code Online (Sandbox Code Playgroud)

你不能直接调用它$ex1->action(),它必须分配给一个变量,然后你可以像函数一样调用这个变量。

  • 这不起作用,您会收到错误消息,没有“Example::action”函数。 (2认同)

Mad*_*iha 0

你所指的是所谓的重载阅读PHP 手册中的所有内容