Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php $this vs函数名_Php_Oop_This_Keyword - Fatal编程技术网

Php $this vs函数名

Php $this vs函数名,php,oop,this,keyword,Php,Oop,This,Keyword,我已经掌握了OOP的窍门,并最终开始在脚本中创建它们。有一件事我不明白,那就是在创建类的实例之后的“$this”。例如,这家伙编码: class Form { protected $inputs = array(); public function addInput($type, $name) { $this->inputs[] = array("type" => $type, "name" => $name); } } $f

我已经掌握了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的方法之外,它不能用于其他方法,对吗

相关的:

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

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

看起来您比编写此代码的人更了解OOP。你喝的是一口受污染的井。哎呀

嗯,我认为代码是错的。最后两行应该是
$form->
而不是
$this->
。可能是重复的我刚刚在PHP文件中复制了代码,它确实生成了一个错误!我想我得更正那个帖子了。
// Correct
$form->addInput("text", "username");
$form->addInput("text", "password");