[英]How is it that a non-static method in PHP can be invoked as if it were static?
See the following code. 请参阅以下代码。 I have defined a non-static method called
bar
in class Foo
. 我在类
Foo
定义了一个称为bar
的非静态方法。 But I am invoking the method as if it were static using the Foo::bar()
syntax. 但是我使用
Foo::bar()
语法调用该方法,就好像它是静态的一样。 It works: http://ideone.com/I45zLx . 它的工作原理: http : //ideone.com/I45zLx 。
<?php
class Foo
{
public function bar()
{
echo "hello, world\n";
}
}
Foo::bar();
?>
Why did I not get a fatal error that I am trying to invoke a non-static method as static? 为什么没有出现致命错误,我试图将非静态方法称为静态方法? Could you please point me to the official PHP documentation which clarifies this point?
您能指出我这一点的官方PHP文档吗?
You won't get a Fatal here , instead a Strict Standard Notice. 您不会在这里收到致命消息,而会收到严格标准通知。
Strict Standards: Non-static method Foo::bar() should not be called statically
严格标准:非静态方法Foo :: bar()不应静态调用
Always enable error_reporting(-1);
始终启用
error_reporting(-1);
on whichever code you test. 在您测试的任何代码上。 You could have seen the above on your output if you had enabled this.
如果启用了此功能,您可能会在输出中看到以上内容。
I think it will generate warning. 我认为它将产生警告。 May be E_STRICT.
可能是E_STRICT。
This main reason to define static method is you can not refer any other public member inside static function with $this object. 定义静态方法的主要原因是您不能使用$ this对象引用静态函数内的任何其他公共成员。
If you try to use $this inside your static function, you'll get a Fatal error: Using $this when not in object context. 如果尝试在静态函数中使用$ this,则会出现致命错误:如果不在对象上下文中使用$ this。
Notion is, static method is about restriction is apply and also how is it handle during program execution. 概念是,静态方法与限制有关,并且在程序执行期间如何处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.