【发布时间】:2017-11-16 14:15:50
【问题描述】:
我正在使用 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 B 这里)?
谢谢。
【问题讨论】:
-
启用错误报告
-
@PeeHaa :如何启用它?我的意思是它的代码是什么?应该在哪里添加对应的代码?
-
在代码顶部使用
ini_set("display_errors",1);来启用错误 -
用
ini_set("display_errors",1);也尝试过使用PHP 7.1.1 的代码,一切正常。很奇怪。
标签: php class object non-static