-1

Possible Duplicate:
What does $this mean in PHP?

What is the use of $this?
I'm getting the result correctly on both the following cases.

  1. Without $this

    class Car {
      function Beetle($colour) {
        return $colour;
      }
    }
    
    $car = new Car();
    
    echo $car->Beetle("Blue");
    
  2. With $this

    class Car {
      function Beetle($colour) {
        $this->colour = $colour;
        return $colour;
      }
    }
    
    $car=new Car();
    
    echo $car->Beetle("Blue");
    

On both the cases, I'm getting the same result: "Blue."
I don't understand why and for what we are using $this.

Community
  • 1
  • 1
Mixin
  • 81
  • 1
  • 1
  • 7

3 Answers3

2

$this refers to the instantiated object that was created with the new operator.

Your first code example just returns the argument ($colour) passed to it.

Your second example assigns the property to its object (with $this) and then returns the argument again.

alex
  • 479,566
  • 201
  • 878
  • 984
  • can you please answer this in simple english pls I told you that I'm a newbie. I know procedural php very well and even created a TIny Clone of Buysellads but this problem is blasting my mind.please help alex.pls pls do your best – Mixin Jun 13 '11 at 08:38
  • @ask What part of it confused you? – alex Jun 13 '11 at 08:53
1

As far as I understannd $this is used to access variables and methods in the class you are in, it is essentially an object of the class. In both your examples you are returning the input parameter anyway.

Without $this;

class Car{

  private $colour;

  function Beetle($colour) {
    return $this->colour;
  }
}

With $this;

class Car{

  private $colour;

  function Beetle($colour) {
    $this->colour = $colour;
    return $this->$colour;
  }
}

What i'm trying to show you here is that in the first example it will return null as the property colour hasn't been set by the function, wheras the second example it sets the property to the input variable and will return the value that is passed in.

In short, $this is how we access properties and methods that belong to the class.

noShowP
  • 830
  • 1
  • 11
  • 22
0

Because you may have multiple instances (objects) of the same class.

class Car {
   var colour;
   var parkedNextTo;
   function setColout($colour)
   {
      $this->colour=$colour;
   }
   function park($nextTo)
   {
      $this->$nextTo=$nextTo;
   }
}

$beetle=new Car();
$beetle->setColour('blue');

$jeep=new Car();
$jeep->setColour('red');
$jeep->nextTo($beetle);
symcbean
  • 47,736
  • 6
  • 59
  • 94