【问题标题】:How to access static property of child class in php? [duplicate]如何在php中访问子类的静态属性? [复制]
【发布时间】:2018-05-23 13:15:23
【问题描述】:
<?php
class A{
    static $var;

    function test(){
      var_dump(self::$var);
    }
}

class B extends A{
    static $var = 'something';
}

$b = new B();
$b->test();
?>

为什么会打印出 null 以及如何解决这个问题?如果我没有将 $var 设置为静态,但我需要它可以在不创建实例的情况下访问它。

【问题讨论】:

  • 这就是 static vs self 发挥作用的地方。如果您将其更改为var_dump(static::$var),它将改为您在子类中的属性。示例:3v4l.org/oviE9

标签: php oop


【解决方案1】:

$b-&gt;test(); 打印 null 因为它是 null。当你这样做时:

class B extends A{
    static $var = 'something';
  }

您实际上并没有对 A 类中的 $var 属性做任何事情。该属性是用 static 关键字定义的,per the docs,“声明为静态的属性不能用实例化的类对象访问(尽管静态方法可以)。”因此,您不能从 B 类继承(或随后设置它)。

如果你想让test()方法输出任何有意义的东西,你需要静态设置,比如:

 A::$var = "something";

【讨论】:

  • “你不能继承 [静态属性]” – 错误:3v4l.org/GotZ4。你把问题搞反了。
猜你喜欢
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 2014-08-27
  • 1970-01-01
相关资源
最近更新 更多