0
<?php

class baseModel
{
    public static function show($className=__CLASS__)
    {
        print_r($className);
    }

    public function test()
    {
        static::show();
    }
}

class AModel extends baseModel 
{
    public static function show($className=__CLASS__)
    {
        print_r($className);
    }
}

class Controller
{
    public function actionTest()
    {
        baseModel::test();
        AModel::test();
    }
}

$c = new Controller;
$c->actionTest();
?>

预期输出:

baseModelAModel

实际输出:

Fatal error: Call to undefined method Controller::show() in /var/www/dashboard/test.php on line 12

为什么 PHP 尝试查找Controller::show()而不是AModel::show

4

2 回答 2

2

static关键字指的是上下文,而不是定义该方法的类。因此,当您A::test从 C 的上下文中调用时,static指的是 C。

于 2013-08-17T14:56:54.843 回答
2

正如它在php手册中所写

在非静态上下文中,被调用的类将是对象实例的类。由于 $this-> 将尝试从同一范围调用私有方法,因此使用 static:: 可能会给出不同的结果。另一个区别是 static:: 只能引用静态属性。

这意味着在对象$c(类)的上下文中,在方法引用对象引用的类中Controller进行非静态调用($c->t())后期绑定static::关键字,该类被称为和不被称为类,而如果调用静态:baseModel::test()$thisController

Controller::test();

的上下文static::称为类。

但是,我建议您不要使用静态调用,除非方法被明确定义为静态:

class baseModel
{
    public static function show($className=__CLASS__)
    {
        print_r($className);
    }

    public static function test() 
    // must be defined as static or context of static:: may change to Controller instead of actual class being called!
    {
        static::show();
    }
}

此代码有效,因为如果明确定义baseModel::test()为静态上下文,static::则始终是静态的。

于 2013-08-17T15:29:41.367 回答