PHP OOP $this Keyword

$this refers to the current object.

$this is a psuedo-variable (also a reserved keyword) which is only available inside methods. And, it refers to the object of the current method.

Let's create a House class with one property (color). Then, create a object from it.

<?php class House { public $color = 'black'; } $house = new House(); Where to use $this? How can we change the value of $color? Take some time and think. There are two ways.

Outside the class. We can directly change the value of a property from outside of the class.

$house -> color = 'white';
Inside the class. We can define a method in the class and call it to change the value of its own property.


public function changeColor() { $this -> color = 'white'; }
$house -> changeColor(); In the second way, we use $this variable to access the current object. Here, the current object is the object saved in $house.
More Examples

Let's play with the $this psuedo-variable.

Here we will create two houses and assign names and colors to them. Then, we will echo it out.

Create the House class

<?php
class House {
public $name;
public $color;
public function setData($name, $color) {
$this -> name = $name;
$this -> color = $color;
}
public function echoData() {
echo "The color of the {$this -> name} is {$this -> color}";
}
}

Create two objects from it

$blackHouse = new House();
$whiteHouse = new House();
Call the setData method with two arguments
$blackHouse -> setData("John's House", "black");
$whiteHouse -> setData("Pearl's House", "white");
Call the echoData to echo out a descriptive phrase
$blackHouse -> echoData();

echo '
';
$whiteHouse -> echoData();
Here's the full code.
PHP OOP $this Keyword Example
<?php
class House {
public $name;
public $color;
public function setData($name, $color) {
$this -> name = $name;
$this -> color = $color;
}
public function echoData() {
echo "The color of the {$this -> name} is {$this -> color}";
}
}
$blackHouse = new House();
$whiteHouse = new House(); // this is a small house, not america's one ;)

$blackHouse -> setData("John's House", "black");
$whiteHouse -> setData("Pearl's House", "white");

$blackHouse -> echoData();
echo '
'; $whiteHouse -> echoData();
Conclusion

We could access the current object with $this keyword. But, we needed to run two steps of code to create a object ($house = new House()) and set its data ($house -> setData(...)). What if we could set the data when we create the object? We can run a constructor function when the object is created. You can learn more in the next chapter.