我只是根据其他语言的经验询问,这些语言可以根据类范围从全局函数调用中消除方法调用的歧义,例如:
class Foo {
function bar(){
echo 'bletch';
}
function baz(){
$this->bar();
}
}
所以我想我在问,是否有另一种方法可以实现$this->bar()
,或者换句话说,我怎么能去掉$this
,在上下文中,它似乎是多余的?
不,如果没有PHP中的$this->
,您就无法从baz()
中访问bar()
,因为您可以很容易地拥有不属于任何类/对象的全局函数bar()
(这与您引用的大多数语言不同),这将导致冲突。
简而言之,这是不可能的。
因为调用bar
会在类外调用一个名为bar
的函数,给定以下内容:
function bar() {
echo 'foo';
}
class Foo {
function bar(){
echo 'bletch';
}
function baz(){
$this->bar();
}
function foobar() {
bar();
}
}
$instance = new Foo();
$instance->foobar();
这将回声function bar()
的foo
而不是method bar()
的bletch