0

有没有办法为另一个类的一个类创建一个类方法?

例子:

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
{

}
4

5 回答 5

2

我不完全确定您实际上可以动态地为类创建方法。如果可以的话,我相信那将是非常糟糕的 OOP 实践。

类本质上是对象的蓝图。我不明白为什么你不能对类中的方法进行编码。

为了停止可能不存在的控制器上的错误(即:edit/),我自己使用以下方法用于我自己的 MVC 框架来检查类中是否存在方法:

$controller = new $class();

if( method_exists( $controller, $this->uri['method'] ) )
    $controller->{$this->uri['method']}( $this->uri['var'] );
else
    $controller->index();   
于 2012-04-18T07:56:18.330 回答
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);
    }
}

PS仅仅是因为我自己已经创建了一个 100% PHP 框架,也许我知道你可能需要什么......

于 2012-04-18T07:54:52.427 回答
1

您可以在超类中声明方法抽象。这意味着期望子类实现抽象方法,但不会提供实际实现。

如果您声明一个方法抽象,那么该类也必须是抽象的。

于 2012-04-18T07:55:20.553 回答
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 ();
于 2012-04-18T07:56:27.257 回答
1

If you have the runkit extension installed, then there's a runkit_method_add feature there.... but this is rarely installed, and shouldn't be used arbitrarily.

于 2012-04-18T07:57:26.783 回答