有没有办法为另一个类的类创建一个类方法?
示例:
class A
{
public function makeMethod()
{
$this->b = new B();
//create a method for class B such as a __call() method
//to catch an error trying to access a non existant class B method
if (!method_exists($this->b, "__call")
// create __call() method
}
}
class B
{
}
答案 0 :(得分:2)
我不完全确定你可以实时为类创建方法。如果可以,我相信这将是非常糟糕的OOP练习。
一个类本质上是一个对象的蓝图。我不明白为什么你不能在类中编写方法。
要在可能不存在的控制器上停止错误(例如:edit /),我自己使用以下内容作为我自己的MVC框架来检查类中是否存在方法:
$controller = new $class();
if( method_exists( $controller, $this->uri['method'] ) )
$controller->{$this->uri['method']}( $this->uri['var'] );
else
$controller->index();
答案 1 :(得分:1)
看一下这个例子:
class A
{
public function makeMethod()
{
$this->b = new B();
//create a method for class B such as a __call() method
//to catch an error trying to access a non existant class B method
$this->b->doit();
}
}
class B
{
public function __call($name,$args)
{
echo "function called: $name with arguments: $args";
}
}
$a = new A();
$a->makeMethod();
?>
这将输出:
function called: doit with arguments: Array
所以,在某种程度上,我们称之为class B
的非存在函数,我们仍然能够做到这一点....在__call
中的class B
方法中,您无法将执行指向某些回调函数(即使是class A
)?为什么“创造”它? (不要从开发人员的角度思考,除非你绝对必须......: - ))
只是一个想法......
Minima Framework中的页面/模块执行处理的一瞥:
public function __call($name, $arguments=NULL)
{
$function_name = "_".$name;
$trace = debug_backtrace();
$moduleCall = false;
if (isset($trace[2]))
{
if (isset($trace[2]['object']))
{
$trace = $trace[2]['object'];
if (is_subclass_of($trace, 'mmModule'))
$moduleCall = true;
}
}
$args = $this->matchArguments($name, $arguments);
if ($moduleCall) { $this->redirect ($name, $arguments); }
else
{
$this->Result = call_user_func_array(array($this, $function_name), $args);
$this->loadTemplate($name);
}
}
P.S。仅仅因为我自己已经创建了一个100%的PHP框架,也许我知道你可能需要什么......
答案 2 :(得分:1)
您可以在超类中声明方法摘要。这意味着期望子类实现抽象方法,但不会提供实际的实现。
如果声明方法抽象,那么该类也必须是抽象的。
答案 3 :(得分:1)
尝试
class A {
public function makeMethod() {
$this->b = new B ();
// create a method for class B such as a __call() method
// to catch an error trying to access a non existant class B method
}
public function __call($method, $args) {
if (isset ( $this->$method )) {
$func = $this->$method;
$func ();
}
}
}
$foo = new A ();
$foo->baba = function () {
echo "Hello Baba";
};
$foo->baba ();
答案 4 :(得分:1)
如果您安装了runkit扩展程序,那么就会有runkit_method_add功能....但这很少安装,不应随意使用。