加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 覆盖静态变量

发布时间:2020-12-13 21:58:41 所属栏目:PHP教程 来源:网络整理
导读:我有两个类(模型和用户),但我有一个问题所以我试图在一个简单的例子中解释它: class person{ protected static $todo ="nothing"; public function __construct(){} public function get_what_todo() { echo self::$todo; }}class student extends person{
我有两个类(模型和用户),但我有一个问题所以我试图在一个简单的例子中解释它:

class person
{
    protected static $todo ="nothing";

    public function __construct(){}

    public function get_what_todo()
    {
        echo self::$todo;
    }
}

class student extends person
{
    protected static $todo ="studing";
}

$s = new student();
$s->get_what_todo(); // this will show the word (nothing)
                     //but I want to show the word (studing)

请给我一个解决方案,但没有在学生班写任何功能我只想在那里做声明:)谢谢:)

解决方法

该原则称为“ late static binding”,并在PHP 5.3.0中引入;使用self关键字访问继承树中调用类中定义的属性,或使用static访问该继承树中子类中定义的属性.

class person
{
    protected static $todo ="nothing";

    public function __construct(){}

    public function get_what_todo()
    {
        echo static::$todo;  // change self:: to static::
    }
}

class student extends person
{
    protected static $todo ="studying";
}

class teacher extends person
{
    protected static $todo ="marking";
}

class guest extends person
{
}

$s = new student();
$s->get_what_todo(); // this will show the "studying" from the instantiated child class

$t = new teacher();
$t->get_what_todo(); // this will show the "marking" from the instantiated child class

$g = new guest();
$g->get_what_todo(); // this will show the "nothing" from the parent class,//    because there is no override in the child class

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读