Tutorials

PHP Magic Method __get() tutorial

Posted by I. B. Gd Pramana A. Putra, 13 Mar 22, last updated 18 Jul 22

In this lesson, we’re going to learn and get familiar with PHP __get() Magic Method tutorial along with example and explanation.

PHP Magic Method: __get() Definition

__get in the PHP programming language is one of the magic methods that will be called upon when an instantiated object of a class is trying to call private or protected properties. In another word, The __get() magic method is called when you try to read data from inaccessible or non-existent object properties.

PHP Magic Method: __get() Declaration

__get() magic method in PHP is declared with the following format:

public __get ( string $name ) : mixed

The declaration format of the __get magic method accepts only one parameter as a string, and could return any data type.

PHP Magic Method: __get() Example

In this example of the __get method use, we will create class “Person” with the following properties and their visibilities, private or protected.

class Person 
{
    private $firstName = "Pramana"; 
    private $lastName = "Adi Putra";
}
We will create an object instance based on that class with the following code example:

$pram = new Person();

echo $pram->firstName . '<br/>';
echo $pram->lastName . '<br/>';

When we execute or run the code, the PHP interpreter will return the following result:

Those error messages have thrown by the interpreter because we tried to read or access data from inaccessible properties that are private or protected. The result will be entirely different if those properties are public.

Now, we will define the __get magic method inside the Person class. As it’s already explained above, this magic method will be executed when the instantiated object tries to read data from inaccessible properties, or a property that has not been defined yet.

On the __get magic method, we will write a statement to tell that the intended object property is non-public or is not exist.

class Person 
{
    private $firstName = "Pramana"; 
    private $lastName = "Adi Putra";
    
    public function __get($key)
    {
        return "Accessed property is either not exist or not a public: " . $key;
    }
}

Now let’s execute the instantiated object again and access those non-public properties:

$pram = new Person();

echo $pram->firstName . '<br/>';
echo $pram->lastName . '<br/>';

The PHP interpreter will return the following result:

The interpreter now returns statements that we’ve written inside the __get magic method. Thus, it’s not returning any bad words that you or other programmers might difficult to understand, instead, it’s returning a clear statement.

Reference: PHP Overloading - PHP.net

Answer & Responses
    No comments yet

Wanna write a response?

You have to login before write a comment to this post.