class 的非静态方法如何在不创建前者对象的情况下从另一个不同的 class' 方法静态调用?
How does the non-static method of a class is getting called statically from another different class' method without creating the object of former?
我正在使用 PHP 7.1.11
考虑以下代码:
<?php
class A {
function foo() {
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "$this is not defined.\n";
}
}
}
class B {
function bar() {
A::foo();
}
}
$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>
以上代码的输出:
$this is defined (A)
$this is not defined.
$this is not defined.
$this is not defined.
除了输出中的第一行之外,接下来的三行输出是通过静态调用 class A
中存在的非静态方法 foo()
生成的(即不创建对象class A
).
谁能解释一下这是怎么回事?
如何从正在考虑的 class 的 class/ 对象静态调用来自另一个 class 的非静态方法(即此处的 class B
)?
谢谢。
Note: PHP is very loose with static vs. non-static methods
但是:不应该静态调用非静态方法(即使 PHP 是容忍的)。为什么?
如果一个方法不是静态的,这通常意味着它依赖于实例的状态,否则它可以被设为静态。
有时非静态方法不依赖于实例,因此程序仍然可以运行,因为此方法可能是静态的。 但你永远不应该这样做。
此外 - 如果您打开错误报告,PHP 也会告诉您:
$this is defined (A)
Deprecated: Non-static method
A::foo() should not be called statically in [...][...] on line
25
$this is not defined.
Deprecated:
Non-static method A::foo() should not be called statically in
[...][...] on line 18
$this is not defined.
Deprecated: Non-static method B::bar() should not be called
statically in [...][...] on line 29
Deprecated: Non-static method A::foo() should not be called
statically in [...][...] on line 18
$this is not
defined.
已弃用还意味着:仅仅因为 PHP 仍然允许这样做,它很可能会在以后的 PHP 更新中被删除。
我正在使用 PHP 7.1.11
考虑以下代码:
<?php
class A {
function foo() {
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "$this is not defined.\n";
}
}
}
class B {
function bar() {
A::foo();
}
}
$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>
以上代码的输出:
$this is defined (A)
$this is not defined.
$this is not defined.
$this is not defined.
除了输出中的第一行之外,接下来的三行输出是通过静态调用 class A
中存在的非静态方法 foo()
生成的(即不创建对象class A
).
谁能解释一下这是怎么回事?
如何从正在考虑的 class 的 class/ 对象静态调用来自另一个 class 的非静态方法(即此处的 class B
)?
谢谢。
Note: PHP is very loose with static vs. non-static methods
但是:不应该静态调用非静态方法(即使 PHP 是容忍的)。为什么?
如果一个方法不是静态的,这通常意味着它依赖于实例的状态,否则它可以被设为静态。
有时非静态方法不依赖于实例,因此程序仍然可以运行,因为此方法可能是静态的。 但你永远不应该这样做。
此外 - 如果您打开错误报告,PHP 也会告诉您:
$this is defined (A)
Deprecated: Non-static method A::foo() should not be called statically in [...][...] on line 25
$this is not defined.
Deprecated: Non-static method A::foo() should not be called statically in [...][...] on line 18
$this is not defined.
Deprecated: Non-static method B::bar() should not be called statically in [...][...] on line 29
Deprecated: Non-static method A::foo() should not be called statically in [...][...] on line 18
$this is not defined.
已弃用还意味着:仅仅因为 PHP 仍然允许这样做,它很可能会在以后的 PHP 更新中被删除。