Getting Properties Through Magic in OOP in PHP
The next magic method we will
look at is called __get
. This
method is triggered when trying to read the value
of a private or protected property.
If you implement the __get
method in any
class, then all accesses to non-existent
or hidden properties will be handled by
this method.
In this case, PHP will automatically pass the name of the requested property as the first parameter of this method, and the value returned by this method will be perceived as the value of the property that was accessed.
It's probably not very clear how this
works yet, so let's look at a practical
example. Suppose we have the following class
Test
with a private and a public
property:
<?php
class Test
{
public $prop1 = 1; // public property
private $prop2 = 2; // private property
}
?>
Let's add the magic method
__get
to our class, which for now will simply
return the name of the property that was accessed:
<?php
class Test
{
public $prop1 = 1;
private $prop2 = 2;
public function __get($property)
{
return $property; // just return the property name
}
}
?>
Let's test the operation of the created magic method. Let's access three types of properties: a public property, a private one, and a non-existent one:
<?php
$test = new Test;
// Access the public property:
echo $test->prop1; // will output 1 - that is, the property value
// Access the private property:
echo $test->prop2; // will output 'prop2' - the property name
// Access a non-existent property:
echo $test->prop3; // will output 'prop3' - the property name
?>
As you can see, our magic method reacts to access to private and non-existent properties, but ignores access to public ones - they work as they did before.