tags:

views:

64

answers:

4

Referring to this question: http://stackoverflow.com/questions/2035449/why-is-oop-hard-for-me

class Form
{
    protected $inputs = array();
    public function makeInput($type, $name)
    {
         echo '<input type="'.$type.'" name="'.$name.'">';
    }

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

    public function run()
   {
       foreach($this->inputs as $array)
       { 
          $this->makeInput($array['type'], $array['name'];
       }
    }
}

$form = new form();

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

Can I get a better explanation of what the $this->input[] is doing in this part:

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

As defined towards the top of the class, $this->inputs is an array. In PHP, you append to an array by putting [] after the array name and assigning to it. So, it is appending to $this->inputs.

Ignacio Vazquez-Abrams
+2  A: 

It's accessing that varible for that instance of the class/object. So let's say you create a new instance of the class by writing $something = new Form(); . Now when you use a function in the class by calling it with $something->functionname(); the function will refence to the $something instance when it say this. The great thing with objects like this is that the functions can access each others varibles.

Hultner
I think I get it, but why can I just call the function like `functionname()`? Why must I use reference the reference it to the instance?
Doug
Because all the functions in the class work together. I got my own rather advanced from class with validation support,etc and there I really benefit from have varibles wich are accessable by all the functions in the class. It's a lot less messy, I can write $form->Validate(); and it will return true if the form validate all the rules I've set up with $form->Rule() without passing any varible to Validate. You might also want to have several instances of the object with different data which can be handy.
Hultner
A: 

$this->inputs = new array() is defining the inputs variable in the current object.

Josh K
A: 
$this->inputs[] = array("type" => $type, "name" => $name);

places at the end of array $this->inputs new element which itself is an array with two elements one with index "type" and other with index "name")

Index of the added element is the highest numerical index in the array $this->input present so far plus one.

$this is an object of class Form and inputs is protected field of this object that becomes an empty array when object is created.

Kamil Szot