【发布时间】:2012-10-31 23:05:49
【问题描述】:
可能重复:
PHP: self vs. $this
我发现我可以通过 $this:: 前缀调用类方法。示例:
class class1 {
public function foo()
{
echo "1";
}
public function bar()
{
$this::foo();
//in this example it acts like $this->foo() and displays "2"
//using self::foo() displays "1"
}
}
class class2 {
public function foo()
{
echo "2";
}
public function bar()
{
class1::bar();
}
}
$obj = new class2();
$obj->bar(); // displays "2"
class1::bar(); // Fatal error
我想知道 $this-> 和 $this:: 前缀调用方法的区别。
ps: 此链接中有一个关于 $this->foo() 和 self::foo() 差异的页面: When to use self over $this?
【问题讨论】:
-
我知道方法的静态调用和实例调用的区别。 $this:: 和 $this-> 行为相同,但 self:: 和 this:: 不同。
-
我不认为这个问题是重复的。它特别关注
$this::。显示的其他链接没有明确讨论$this::。 (对此,简单的答案是“不要使用那种语法——这似乎是 PHP 定义$this和::的意外或非显而易见的结果。相反,请坚持使用$this->、self::、或static::,取决于你想要表达的意思。)