我正在尝试从外部文件动态添加方法.现在我__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)
任何建议将被认真考虑.
这是你需要的吗?
$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(),它必须分配给一个变量,然后你可以像函数一样调用这个变量。