我有 Java 背景,最近在 PHP 中测试了一些 OOP 方法。我发现父类可以使用子类属性。下面的代码描述了我想说的内容。
<?php
class ParentClass {
public static function test() {
echo "hello world ". implode(',', static::$prop);
}
}
class ChildClass extends ParentClass {
public static $prop = ['a' , 'b'];
}
ChildClass::test();
?>
在上面的代码中,ParentClass 使用其函数 test()
中的 $prop 变量。这只是简单地输出,没有错误。然而,这在 Java 中是不允许的。 PHP 这种方法背后的原因是什么?
最佳答案
Java没有Late static bindings的概念:
"Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information.
如果您使用 self::
,您将获得与 Java 中相同的行为。但是 static::
在运行时解析。
关于java - 在php中从父类访问子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21060633/