PHP Magic Methods

Summary: in this tutorial, we will introduce you some important PHP magic methods that you can use to deal with accessing the non-existent members and methods.

PHP __get() and __set() methods

PHP provides a pair of magic methods that deal with non-existent or private property access:

  • The __get() method is called whenever you attempt to read a non-existing or private property of an object.
  • The __set() method is called whenever you attempt to write to a non-existing or private property of an object.

Let’s take a look at the following example:

How it works.

  • First, we attempted to write and read a private property: $firstName.  The method __get() and __set() methods are called automatically.
  • Second, we attempted to write and read a non-existing property: $lastName. The method __get() and __set() methods are also called automatically.

The __get() and __set() methods are used to define properties of a class as an associative array instead of separate properties. The following example demonstrates the idea:

By using the __get() and __set() method, the Person class can hold any number of  “virtual” properties.

PHP __call() method

Similar to the __get() and __set() methods, the __call() magic method is called automatically when a nonexistent method of the class is called. The __call() method is rarely used in practice. It is useful when you to create a wrapper class that wraps the existing APIs.

The following example illustrates a simple string class that supports three methods: strlen(), strtoupper() and strtolower().

How it works.

  • Whenever you call a nonexistent method, the __call() method is called automatically. Inside the __call() method, we check to see if the calling method is supported, which is defined in the $APIs array. If it is, we execute the corresponding string function, otherwise, we issue a message.

PHP uses double underscores ( __ )  as a prefix for the magic methods in the class so it is recommended that you should not use the method name that begins with double underscores ( __ ).

Notice that the constructor and destructor methods ( __construct() and __destruct() ) are also magic methods. For other magic methods, check it out the PHP magic methods.

In this tutorial, you have learned how to use three PHP magic methods:__get() __set() and __call() that deals with non-existent members and methods of a class.

  • Was this tutorial helpful ?
  • YesNo