为什么 PHP 允许使用类名以及通过作为类名占位符的各种关键字(例如 self、static 和parent)静态调用非静态方法?
But on the other hand it does not allow calling non-static properties statically?
这是示例代码-
<?php
# PHP Version 7.1.7
error_reporting(E_ALL);
ini_set('display_errors', 1);
class Fruit {
public $name = 'Fruit';
public function x() {
echo "Fruit_x" . "<br>";
}
}
class Orange extends Fruit {
public $name = 'Orange';
public function x() {
echo "Orange_x" . "<br>";
parent::x();
self::y();
static::z();
// Code Below will throu Uncaught Error: Access to undeclared static property
// echo parent::$name . "<br>";
// echo self::$name . "<br>";
}
public function y(){
echo "Y" . "<br>";
}
public function z(){
echo "Z" . "<br>";
}
}
(new Orange)->x(); // No Warnings
Orange::x(); // However calling like this shows warning as of PHP 5 & 7
// Docs - http://php.net/manual/en/language.oop5.static.php
?>
最佳答案
根据您的评论,我相信您的误解来自于您认为 parent::
和 self::
始终用于进行静态调用。
Parent 用于访问任何类型的父方法,而 self 用于始终使用当前类方法。由于方法只能定义一次,PHP 可以推断应该如何调用这些方法。
https://3v4l.org/NJOTK将显示 $this->call()
、self::call()
和 parent::call()
之间差异的示例> 使用继承时。允许使用 static::
,但在功能上等同于实例方法的 $this->
。
相同的行为不会扩展到属性。实例属性不支持相同级别的继承,它们仅继承实例化时的值。您无法访问父级的属性,该实例上仅存在一个属性。因此,始终使用 $this->property
访问非静态属性。
关于php - 为什么PHP允许静态调用非静态方法但不允许静态调用非静态属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699265/