使用PHP 5.3中的实例方法的奇怪结果
想知道下面的例子是如何实际工作的,以及如何能够动态地做这样的事情.使用call_user_func或call_user_func_array不允许这种情况发生.
<?php class Person { public $name = "George"; public function say_hi() { return ExtraMethods::hi(); } } class ExtraMethods { public function hi() { return "Hi,".$this->name; } } $george = new Person(); echo $george->say_hi(); ?> 这应该导致: Hi,George 想知道为什么实例方法hi不仅可以静态调用(不会感到惊讶,这可能发生在PHP中),但为什么我能够使用$this 解决方法
从
manual:
所以,根据第二部分,按设计.请记住它虽然使用了实际的对象实例(换句话说,如果你添加public $name =“SomethingElse”;对于ExtraMethods,结果仍然是Hi,George). 静态调用该方法不是正确的编码,但PHP会原谅您,并且只发出严格错误: "Strict Standards: Non-static method ExtraMethods::hi() should not be called statically,assuming $this from incompatible context in ..." 当然,在这种情况下,只是将对象作为参数传递将更加清晰和可取. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |