2011-08-11 37 views
16

我试图从外部文件动态添加方法。 现在我在我的课上有__call方法,所以当我打电话给我想要的方法时,__call包含了我的方法;问题是我想通过使用我的类调用加载函数,并且我不希望在类之外加载函数;如何动态添加方法

Class myClass 
{ 
    function__call($name, $args) 
    { 
     require_once($name.".php"); 
    } 
} 

echoA.php:

function echoA() 
{ 
    echo("A"); 
} 

的话,我想用它喜欢:

$myClass = new myClass(); 
$myClass->echoA(); 

任何意见,将不胜感激。

+0

从php [手册](http://www.php.net/manual/functions.user-defined.php):*“... PHP中的所有函数和类都具有全局范围。 ..“*。所以至少:*“...而且我不想在课堂外加载函数; ...”*是不可能的。 – Yoshi

+0

这听起来像个坏主意...... – deceze

+0

@Yoshi我想我没有解释清楚,当我包含包含该函数的文件时,它可以在任何地方调用,如:echoA();而不是$ myClass-> echoA(); –

回答

0

什么你指的是被称为重载。阅读所有关于它的PHP Manual

2

如果我阅读本手册的权利, 的__call得到所谓insted的功能,如果函数存在不到风度所以 你probely需要调用它,你创建之后

Class myClass 
{ 
    function __call($name, $args) 
    { 
     require_once($name.".php"); 
     $this->$name($args); 
    } 
} 
+2

您不能在执行时向php类添加方法。 – Yoshi

+0

我试了2个小时前,我们不能通过包含一个包含函数的文件添加方法,这就是为什么我问这个问题;) –

+0

我认为这可能是有效的答案,除了require_once方法来调用动态函数似乎没有办法走。我正在使用__call魔术方法有条件地创建一个方法。 –

-3

我已经处理了下面的代码示例和一个帮助方法,它可以与__call一起使用,这可能证明是有用的。 https://github.com/permanenttourist/helpers/tree/master/PHP/php_append_methods

+3

请注意,[链接只是答案](http://meta.stackoverflow.com/tags/link-only-answers/info)不鼓励,所以答案应该是搜索解决方案的最终点(vs.而另一个引用的中途停留时间往往会随着时间推移而过时)。请考虑在此添加独立的摘要,并将链接保留为参考。 – kleopatra

+0

链接处于脱机状态。 – mheinzerling

2

您可以动态地添加属性,并提供它是通过以同样的方式构造函数中完成的方法,你可以将一个函数作为另一个函数的参数。

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

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

$ex1 = new class('fun'); 

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

+0

请在这里发布一个重要部分 – VladL

0

您可以创建在您的类属性:methods=[]
和使用create_function为创建lambda函数。
将其存储在methods属性中,位于所需方法名称的索引处。
使用:

function __call($method, $arguments) 
{ 
    if(method_exists($this, $method)) 
     $this->$method($arguments); 
    else 
     $this->methods[$method]($arguments); 
} 

查找和调用好方法。

1

这是你需要什么?

$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();