从继承中获取静态函数

时间:2017-09-17 13:36:11

标签: php yii2 php-5.6

当我使用

DemoStyle::order(); // returns {{%demo_style}} but not 'site.site_demo_style'
DemoLayout::order(); // returns {{%demo_layout}} but not 'site.site_demo_layout'

我的表名错了。 我相信它是ActiveRecord :: tableName()返回错误的名称。 如何从DemoStyle和DemoLayout获取tableName。

class Sortable extends ActiveRecord
{
    public static function order()
    {
        return self::tableName();
    }
}

class DemoStyle extends Sortable
{
    public static function tableName()
    {
        return 'site.site_demo_style';
    }
}

class DemoLayout extends Sortable
{
    public static function tableName()
    {
        return 'site.site_demo_layout';
    }
}

请不要投票。

2 个答案:

答案 0 :(得分:0)

<强>更新

为什么使用静态方法?当您定义抽象方法并且不使用静态上下文时,这对我有用:

 <?php
    abstract class Sortable 
    {
        public abstract function tableName();


        public function order()
        {
            return $this->tableName();
        }
    }

    class DemoStyle extends Sortable
    {
        public function tableName()
        {
            return 'site.site_demo_style';
        }
    }

    class DemoLayout extends Sortable
    {
        public function tableName()
        {
            return 'site.site_demo_layout';
        }
    }

echo (new DemoStyle)->order();

更新2

静态上下文的php文档中的示例:Late Static Bindings

答案 1 :(得分:0)

在这种情况下工作

static::tableName()