$this 与函数名
我正在掌握 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-对我来说很困难/3689613#3689613
I am getting a hang of OOP and finally started creating them in my scripts. One thing I don't get it is the "$this" after creating an instance of class. For example, this guy coded:
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");
Notice that the last two lines show that he used $this->addInput().
How is it different from $form->addInput? I always used the name of variable I use to create an instance of class. I don't see what $this->function() does. How does the PHP know which object it's referring to?
From what I understand, $this->var is used in any methods within that object. If there's no $this->var but rather plain $variable then it cannot be used in other methods other than the method that has that $variable, correct?
related: https://stackoverflow.com/questions/2035449/why-is-oop-hard-for-me/3689613#3689613
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此代码不正确。当您不在类方法中时,就没有
$this
。那应该是$form
。所以回答你的问题:区别在于$form->addInput
是正确的,而$this->addInput
是无效的!看起来你比编写这段代码的人更了解 OOP。你正在喝一口受污染的井里的水。哎呀!
This code is incorrect. There is no
$this
when you're not in a class method. That should be$form
. So to answer your question: the difference is that$form->addInput
is correct and$this->addInput
is invalid!It looks like you understand OOP better than the person who wrote this code. You're drinking from a tainted well. Yikes!