我正在尝试从外部文件动态添加方法。现在我的类中有__call方法,所以当我调用我想要的方法时,__call会为我包含它;问题是我想通过我的类调用加载的函数,而我不想在类之外加载函数;
Class myClass
{
function__call($name, $args)
{
require_once($name.".php");
}
}echoA.php:
function echoA()
{
echo("A");
}然后我想像这样使用它:
$myClass = new myClass();
$myClass->echoA();任何建议都将不胜感激。
发布于 2015-05-04 20:17:08
这是你需要的吗?
$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();发布于 2014-09-17 15:52:28
你可以动态地添加属性和方法,只要它是通过构造函数完成的,就像你可以将一个函数作为另一个函数的参数传递一样。
class Example {
function __construct($f)
{
$this->action=$f;
}
}
function fun() {
echo "hello\n";
}
$ex1 = new class('fun');你不能直接调用$ex1->action(),它必须被赋给一个变量,然后你才能像调用函数一样调用这个变量。
发布于 2011-08-11 21:21:09
如果我没看错手册,__call会调用函数的insted,如果函数不存在,那么您可能需要在创建它之后调用它
Class myClass
{
function __call($name, $args)
{
require_once($name.".php");
$this->$name($args);
}
}https://stackoverflow.com/questions/7026487
复制相似问题