views:

64

answers:

1

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

+3  A: 
// 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!

John Kugelman
I just copied the code in PHP file and it did generate an error! I guess I'll have to correct that posting.
netrox