In the first tutorial of this series, we learned how to group the code related to a certain topic into one single class. For example, we wrote an Animal class that groups the code.

class Animal {
    public $family;
    public $food;

public function description(){
    return ‘Four legged Animals.’;
}

}

We also created two objects out of the class in order to be able to use its code.

$cow = new Animal();
$lion = new Animal();

$this is a pseudo variable (also a reserved keyword) which is used inside a class. Generally within the method to access non-static member of class (variables or functions) for the current object.

  • In Php this keyword should be preceded with a $ sign while referring a class member.
  • $this variable uses dash and greater than (->), as we have used with object instance to access the class properties and methods of that object. For example $this->propertyName, $this->method();
  • $this is used for accessing non-static member with -> operator.
  • But, $this will refer class members for a particular instance of the class.

Let’s illustrate $this keyword on the Animal class

In order to approach the property $family, we use:

$this->family;

In order to approach the property $food, we use:

$this->food;

Then the description method would look like

class Animal {

	//Properties
  public $family;
  public $food;

	//Methods
	public function description(){
	    return 'I am from family ' . $this->family . ' and I eat ' .$this->food;
	}
}

Now, Let us create two object from the class;

$cow = new Animal();
$lion = new Animal();

And set the value for the class property

$cow->food = 'Grass';
$lion->food = 'Meat';
$cow->family = 'Herbivore';
$lion->family = 'Carnival';

We can call the description() method for the object cow.

echo $cow->description();
Result:
I am from family Herbivore and I eat Grass

This is how the full code looks like

<?php

//declare class
class Animal {

	//Properties
  public $family;
  public $food;

	//Methods
	public function description(){
	    return 'I am from family ' . $this->family . ' and I eat ' .$this->food;
	}
}

$cow = new Animal();
$lion = new Animal();

$cow->food = 'Grass';
$lion->food = 'Meat';
$cow->family = 'Herbivore';
$lion->family = 'Carnival';

echo $cow->description();
?>

Conclusion

In this tutorial, you have learned how to use the $this keyword in order to get the class’s own properties and methods from within the class. In the next tutorial, you will learn about the Chaining Methods and Properties that enables us to approach properties and methods within the scope of the class.

If you have any questions, feel free to ask in the comments below .

If this tip has been helpful to you, please spend a second of your time and share it using the buttons below… thanks!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *