在 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
>
Wondering how the example below is actually working, and how one would be able to do something like dynamically. Using call_user_func
or call_user_func_array
doesn't allow this to happen.
<?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();
?>
this should result with:
Hi, George
Wondering why the instance method hi
can be called not only statically (not surprised that this can happen in PHP), but why I am able to use $this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自手册:
因此,根据第二部分,按照设计。请记住,它使用现有的实际对象实例(换句话说,如果将
public $name = "SomethingElse";
添加到ExtraMethods
,结果仍然是嗨,乔治
)。静态调用该方法不是正确的编码,但 PHP 会原谅您,并且仅发出严格错误:
当然,在这种情况下,仅将对象作为参数传递会更加清晰和可取。
From the manual:
So, according to the second portion, by design. Keep in mind it uses the actual object instance in existance though (in other words, if you add
public $name = "SomethingElse";
toExtraMethods
, the result would still beHi, George
).Calling the method statically is not proper coding, but PHP forgives you, and issues only a Strict Error:
Of course, in this instance, just passing the object as an argument would be far clearer and preferable.