为什么PHP允许静态地使用类名并通过各种关键字调用非静态方法,比如自、静态和父类,它们是类名的占位符?
但另一方面,它不允许静态调用非静态属性?
这是样本代码-
<?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
?>

发布于 2018-08-06 00:57:14
基于您的评论,我相信您的误解来自于这样一个事实:您认为parent::和self::总是用于进行静态调用。
父方法用于访问任何类型的父方法,而self用于始终使用当前类方法。因为方法只能定义一次,所以PHP可以推断如何调用这些方法。
https://3v4l.org/NJOTK将显示$this->call()、self::call()和parent::call()在使用继承时的区别。允许使用static::,但功能上等同于$this-> (例如)方法。
相同的行为不会扩展到属性。实例属性不支持相同级别的继承,它们只在实例化时继承值。不能访问父级的属性,该实例上只存在一个属性。因此,非静态属性总是使用$this->property访问的.
https://stackoverflow.com/questions/51699265
复制相似问题