gpt4 book ai didi

php - 覆盖静态变量

转载 作者:可可西里 更新时间:2023-11-01 00:00:04 26 4
gpt4 key购买 nike

我有两个类(模型和用户)但是我有一个问题所以我试着用一个简单的例子来解释它:

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)

请给我一个解决方案,但我不想在学生类(class)写任何函数,我只想在那里做声明 :) 谢谢 :)

最佳答案

原理称为“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 $todo is not overriden in the child class

关于php - 覆盖静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36308465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com