How to access classes and objects in PHP

In the previous article Classes and objects in PHP we have explained how classes and objects are defined and created. Now let's learn how to access to the class members. In PHP there's a special operator for these purposes. Here is an example:
// Creating new class Coordinates: class Coordinates { // data (properties): var $name; // methods: function Getname() { echo '<h1>Justine</h1>'; } } // Creating an object of the class Coordinates: $object = new Coordinates; // Getting access to new class members: $object->name = 'Brian'; echo $object->name; // Output 'Brian' // And now we gain access to the class method (actually to the function inside the class): $object->Getname(); // Output 'Justine' in capital letters
To gain access to the class members within a class, you must use the pointer $this, which always refers to the current object. The modified Getname() method:
function Getname() { echo $this->name; }
In the same way, you can write the method Setname():
function Setname($name) { $this->name = $name; }
And now, in order to change the name, use the method Setname():
$object->Setname('Peter'); $object->Getname();
And here is the complete code:
// Creating a new class Coordinates: class Coordinates { // data (properties): var $name; // methods: function Getname() { echo $this->name; } function Setname($name) { $this->name = $name; } } // Creating class object Coordinates: $object = new Coordinates; // Now to change the name use the method Setname(): $object->Setname('Kevin'); // And to gain access, as usual, use Getname(): $object->Getname(); // The script outputs 'Kevin'
The pointer $this can be used not only to gain access to methods, but also to access data:
function Setname($name) { $this->name = $name; $this->Getname(); }