为什么PHP允许静态调用非静态方法但不允许静态调用非静态属性?
Why does PHP allow calling non-static methods statically but does not allow calling non-static properties statically?
为什么 PHP 允许使用 Class 名称和作为 Class 名称占位符的各种关键字(例如 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
?>
You can Run Code in the Browser to see the following Result
根据您的评论,我认为您的误解是因为您认为 parent::
和 self::
总是用于进行静态调用。
Parent 用于访问任何类型的父方法,而 self 用于始终使用当前的 class 方法。由于方法只能定义一次,PHP 可以推断出应该如何调用这些方法。
https://3v4l.org/NJOTK 将显示使用继承时 $this->call()
、self::call()
和 parent::call()
之间差异的示例。 static::
是允许的,但在功能上等同于实例方法的 $this->
。
相同的行为不会扩展到属性。实例属性不支持同级继承,它们只在实例化时继承值。您无法访问父项的 属性,该实例上只存在一个 属性。因此,总是使用 $this->property
.
访问非静态属性
为什么 PHP 允许使用 Class 名称和作为 Class 名称占位符的各种关键字(例如 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
?>
You can Run Code in the Browser to see the following Result
根据您的评论,我认为您的误解是因为您认为 parent::
和 self::
总是用于进行静态调用。
Parent 用于访问任何类型的父方法,而 self 用于始终使用当前的 class 方法。由于方法只能定义一次,PHP 可以推断出应该如何调用这些方法。
https://3v4l.org/NJOTK 将显示使用继承时 $this->call()
、self::call()
和 parent::call()
之间差异的示例。 static::
是允许的,但在功能上等同于实例方法的 $this->
。
相同的行为不会扩展到属性。实例属性不支持同级继承,它们只在实例化时继承值。您无法访问父项的 属性,该实例上只存在一个 属性。因此,总是使用 $this->property
.