2010-11-08 184 views
10

可能重复:
PHP: self vs this

你好, 你能帮我理解PHP变量名$this的意思吗?

谢谢你的帮助。

+2

可能重复:http://stackoverflow.com/questions/151969/php-self-vs-this。另外,请不要在提问中太可爱。 ;) – birryree 2010-11-08 15:00:18

+2

祝贺您在12岁时扩大知识!但由于这与问题无关,您可以编辑该问题以将其删除吗? – 2010-11-08 15:02:07

+0

似乎堆栈溢出的人不知道'我12岁,这是什么'是指。 – JAL 2010-11-08 15:06:25

回答

16

$this是指你在课堂上。

例如

Class Car { 

    function test() { 
     return "Test function called"; 
    } 

    function another_test() { 
     echo $this->test(); // This will echo "Test function called"; 
    } 
} 

希望这有助于。

+0

这是一种引用自身的方法...或调用方法或从本身读取变量。 – jodm 2010-11-08 15:02:47

+5

实际上,self指您当前所在的类。$ this指的是您所在类的当前对象实例。 – 2010-11-08 15:02:49

+0

它不会'echo“测试函数称为”',因为您正在访问'test'成员变量(不存在),而不是方法'test()'。你需要将它改为'echo $ this-> test()'... – ircmaxell 2010-11-08 15:03:01

1

$this是在对象中使用的受保护变量,$this允许您在内部访问类文件。

Class Xela 
{ 
    var age; //Point 1 

    public function __construct($age) 
    { 
     $this->setAge($age); //setAge is called by $this internally so the private method will be run 
    } 

    private function setAge($age) 
    { 
     $this->age = $age; //$this->age is the variable set at point 1 
    } 
} 

它基本上是一个变量范围的问题,$this只允许已启动,是指对象,只有其父母,你可以运行私有方法和设置私有变量,其中一个对象中因为你无法做到这一点。

self关键字是非常相似的除了它指的是静态方法类中,静态基本上意味着你不能使用$this作为它不是一个对象是,你必须使用self::setAge();,如果该setAge方法声明为static那么你不能从该对象的瞬间/叫它object

一些链接供你上手:

+0

虽然我知道你正在向OOP新人解释,但请不要将对象称为类。 $ this用于引用对象属性和方法,而self ::用于引用类属性和方法。 我认为重要的是要解释两者之间的差异。 – Craige 2010-11-08 15:24:48