self :: in php

self:: in php

‘$this’ is a good way of referencing properties, but how do we reference Methods? Remember, a Method is a function inside an object, and gives the Object the ability to DO THINGS.
So, in order to call a Method of the Object I am working in, I can use the self:: call, as below:

<?php

class human {
public $gender;

public function __construct($gender)
{
$this->gender = $gender;

echo self::get_gender();
}

public function get_gender()
{
return $this->gender;
}
}

?>

What you will see now is that once the object is instantiated, it sets the value of $gender, and then runs the get_gender() function, which prints the following to the screen:
Male
This makes setting up and running methods in a current class very simple.

Leave a Reply