$ this vs function name

时间:2010-10-16 23:32:35

标签: php oop this keyword

我正在获取OOP,最后开始在我的脚本中创建它们。在创建类的实例之后,我得不到的一件事就是“$ this”。例如,这个人编码:

class Form
{
protected $inputs = array();    

public function addInput($type, $name)
{
     $this->inputs[] = array("type" => $type,
            "name" => $name);
}


}

 $form = new form();

 $this->addInput("text", "username");
 $this->addInput("text", "password");

请注意,最后两行显示他使用了$ this-> addInput()。

与$ form-> addInput有何不同?我总是使用我用来创建类实例的变量名。我没有看到$ this-> function()的作用。 PHP如何知道它指的是哪个对象?

根据我的理解,$ this-> var用于该对象中的任何方法。如果没有$ this-> var而是普通的$ variable,那么除了具有该$ variable的方法之外,它不能用于其他方法,对吗?

相关:https://stackoverflow.com/questions/2035449/why-is-oop-hard-for-me/3689613#3689613

1 个答案:

答案 0 :(得分:3)

// Incorrect
$this->addInput("text", "username");
$this->addInput("text", "password");

此代码不正确。当你不在类方法中时,没有$this。那应该是$form。所以回答你的问题:区别在于$form->addInput是正确的,$this->addInput无效!

// Correct
$form->addInput("text", "username");
$form->addInput("text", "password");

看起来你比编写这段代码的人更了解OOP。你是从一个受污染的井里喝水的。糟糕!