【问题标题】:Static methods and inheritance: why value of static property of one class goes to another?? 'get_called class'静态方法和继承:为什么一个类的静态属性的值转到另一个类? 'get_call 类'
【发布时间】:2017-01-06 13:29:38
【问题描述】:

我有一个代码:

<?php

abstract class Model
{
    static protected $_table;

    static public function setTable()
    {
        self::$_table = get_called_class();
    }

    static public function getTable()
    {
        if(!isset(self::$_table)) {
            self::setTable();
        }
        return self::$_table;
    }

}

class User extends Model {}
class Post extends Model {}

echo User::getTable();
echo "<br>";
echo Post::getTable();

?>

回显它的输出是:“用户用户”。我不明白为什么一个班级的财产价值会转移到另一个班级。为什么第二个回声不给出“发布”输出?我哪里错了?

【问题讨论】:

    标签: php inheritance static-methods


    【解决方案1】:

    因为您使用的是静态属性,所以在第一次设置 Model::$_table 后,您的类不会再次设置它。除非您更改您的 Model::getTable() 函数,以便它每次都调用 self::setTable()

    您还可以将Model 创建为特征而不是传统的类。

    例如:

    trait class Model
    {
        static protected $_table;
    
        static public function setTable()
        {
            self::$_table = get_called_class();
        }
    
        static public function getTable()
        {
            if(!isset(self::$_table)) {
                self::setTable();
            }
            return self::$_table;
        }
    
    }
    
    class User {
        use Model;
    }
    
    class Post {
        use Model;
    }
    
    echo User::getTable();
    echo "<br>";
    echo Post::getTable();
    

    【讨论】:

    • 谢谢,它解释了一点。我仍然无法理解为什么 User 和 Post 类具有共同的属性而不是具有单独的价值。我设置了用户的表名,为什么还要设置 Post 表?就像从 Model 类继承的每个类只有一个静态属性 $_table...
    • 静态类属性的行为与非静态类属性不同。因此名称static 这些属性是持久的。你可能想看看at the example in the php docs 可以帮助你重组你当前的课程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2015-12-12
    相关资源
    最近更新 更多