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: http://stackoverflow.com/questions/2035449/why-is-oop-hard-for-me/3689613#3689613


Um, I think that code is wrong. It should defiantly be $form-> not $this-> for the last 2 lines.

Written by Petah

possible duplicate of what does $this mean within a class definition?

Written by Gordon

Accepted Answer

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

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!

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

It looks like you understand OOP better than the person who wrote this code. You're drinking from a tainted well. Yikes!

Written by John Kugelman
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki