1. Code
  2. PHP

Deciphering Magic Methods in PHP

Scroll to top
16 min read

PHP provides a number of 'magic' methods that allow you to do some pretty neat tricks in object oriented programming. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met. Magic methods provide some extremely useful functionality, and this tutorial will demonstrate each method's use.


Before We Begin

In order to fully understand magic methods, it's helpful to see them in action. So let's start with a base set of very simple classes. Here we define two classes: Device and Battery.

1
<?php
2
class Device {
3
    public $name;           // the name of the device

4
    public $battery;        // holds a Battery object

5
    public $data = array(); // stores misc. data in an array

6
    public $connection;     // holds some connection resource

7
8
    protected function connect() {
9
        // connect to some external network

10
        $this->connection = 'resource';
11
        echo $this->name . ' connected' . PHP_EOL;
12
    }
13
14
    protected function disconnect() {
15
        // safely disconnect from network

16
        $this->connection = null;
17
        echo $this->name . ' disconnected' . PHP_EOL;
18
    }
19
}
20
21
class Battery {
22
    private $charge = 0;
23
24
    public function setCharge($charge) {
25
        $charge = (int)$charge;
26
        if($charge < 0) {
27
            $charge = 0;
28
        }
29
        elseif($charge > 100) {
30
            $charge = 100;
31
        }
32
        $this->charge = $charge;
33
    }
34
}
35
?>

If words like "method" and "property" sound alien to you, you might want to read up on this first.

Device objects will hold a name, a Battery object, an array of data, and a handle to some external resource. They also have methods for connecting and disconnecting the external resource. Battery objects simply store a charge in a private property and have a method to set the charge.

This tutorial assumes you have a basic understanding of object oriented programming. If words like "method" and "property" sound alien to you, you might want to read up on that first.

These classes are pretty useless, but they make a good example for each of the magic methods. So now that we have our simple classes created, we can try out the magic methods.


Constructors & Destructors

Constructors and destructors are called when an object is created and destroyed, respectively. An object is "destroyed" when there are no more references to it, either because the variable holding it was unset/reassigned or the script ended execution.

__construct()

The __construct() method is by far the most commonly used magic method. This is where you do any initialization you need when an object is created. You can define any number of arguments here, which will be passed when creating objects. Any return value will be passed through the new keyword. Any exceptions thrown in the constructor will halt object creation.

1
class Device {
2
    //...

3
    public function  __construct(Battery $battery, $name) {
4
        // $battery can only be a valid Battery object

5
        $this->battery = $battery;
6
        $this->name = $name;
7
        // connect to the network

8
        $this->connect();
9
    }
10
    //...

11
}

Declaring the constructor method 'private' prevents external code from directly creating an object.

Here we have declared a constructor that accepts two arguments, a Battery and a name. The constructor assigns each of the properties that the objects requires to function and runs the connect() method. The constructor allows you to ensure that an object has all the required pieces before it can exist.

Tip: Declaring the constructor method 'private' prevents external code from directly creating an object. This is handy for creating singleton classes that restrict the number of objects that can exist.

With the above constructor in place, here is how you create a Device called 'iMagic':

1
$device = new Device(new Battery(), 'iMagic');
2
// iMagic connected

3
echo $device->name;
4
// iMagic

As you can see, arguments passed to the class are actually being passed to the constructor method. You can also tell that the connect method was called and the $name property was populated.

Let's say we forget to pass a name. Here's what happens:

1
$device = new Device(new Battery());
2
// Result: PHP Warning:  Missing argument 2 for Device::__construct()

__destruct()

As the name implies, the __destruct() method is called when the object is destroyed. It accepts no arguments and is commonly used to perform any cleanup operations such as closing a database connection. In our case, we'll use it to disconnect from the network.

1
class Device {
2
    //...

3
    public function  __destruct() {
4
        // disconnect from the network

5
        $this->disconnect();
6
        echo $this->name . ' was destroyed' . PHP_EOL;
7
    }
8
    //...

9
}

With the above destructor in place, here is what happens when a Device object is destroyed:

1
$device = new Device(new Battery(), 'iMagic');
2
// iMagic connected

3
unset($device);
4
// iMagic disconnected

5
// iMagic was destroyed

Here, we've destroyed the object using unset(). Before it is destroyed, the destructor calls the disconnect() method and prints a message, which you can see in the comments.


Property Overloading

Note: PHP's version of "overloading" is not quite the same as most other languages, though the same results can be reached.

This next set of magic methods are about dealing with property access, defining what happens when you try to access a property that does not exist (or is not accessible). They can be used to create pseudo properties. This is called overloading in PHP.

__get()

The __get() method is called when code attempts to access a property that is not accessible. It accepts one argument, which is the name of the property. It should return a value, which will be treated as the value of the property. Remember the $data property in our Device class? We'll be storing these "pseudo properties" as elements in the data array, and we can let users of our class access them via __get(). Here's what it looks like:

1
class Device {
2
    //...

3
    public function  __get($name) {
4
        // check if the named key exists in our array

5
        if(array_key_exists($name, $this->data)) {
6
            // then return the value from the array

7
            return $this->data[$name];
8
        }
9
        return null;
10
    }
11
    //...

12
}

A popular use of the __get() method is to extend the access control by creating "read-only" properties. Take our Battery class, for example, which has a private property. We can allow the private $charge property to be read from outside code, but not changed. The code would look like this:

1
class Battery {
2
    private $charge = 0;
3
4
    public function  __get($name) {
5
        if(isset($this->$name)) {
6
            return $this->$name;
7
        }
8
        return null;
9
    }
10
    //...

11
}

In this example, note the use of variable variables to dynamically access a property. Assuming the value 'user' for $name, $this->$name translates to $this->user.

__set()

The __set() method is called when code attempts to change the value a property that is not accessible. It accepts two arguments, which are the name of the property and the value. Here's what that looks like for the "pseudo variables" array in our Device class:

1
class Device {
2
    //...

3
    public function  __set($name, $value) {
4
        // use the property name as the array key

5
        $this->data[$name] = $value;
6
    }
7
    //...

8
}

__isset()

The __isset() method is called when code calls isset() on a property that is not accessible. It accepts one argument, which is the name of the property. It should return a Boolean value representing the existence of a value. Again using our variable array, here's what that looks like:

1
class Device {
2
    //...

3
    public function  __isset($name) {
4
        // you could also use isset() here

5
        return array_key_exists($name, $this->data);
6
    }
7
    //...

8
}

__unset()

The __unset() method is called when code attempts to unset() a property that is not accessible. It accepts one argument, which is the name of the property. Here's what ours looks like:

1
class Device {
2
    //...

3
    public function  __unset($name) {
4
        // forward the unset() to our array element

5
        unset($this->data[$name]);
6
    }
7
    //...

8
}

Property Overloading in Action

Here are all of the property related magic methods we have declared:

1
class Device {
2
    //...

3
    public $data = array(); // stores misc. data in an array

4
    //...

5
    public function  __get($name) {
6
        // check if the named key exists in our array

7
        if(array_key_exists($name, $this->data)) {
8
            // then return the value from the array

9
            return $this->data[$name];
10
        }
11
        return null;
12
    }
13
14
    public function  __set($name, $value) {
15
        // use the property name as the array key

16
        $this->data[$name] = $value;
17
    }
18
19
    public function  __isset($name) {
20
        // you could also use isset() here

21
        return array_key_exists($name, $this->data);
22
    }
23
24
    public function  __unset($name) {
25
        // forward the unset() to our array element

26
        unset($this->data[$name]);
27
    }
28
    //...

29
}

With the above magic methods, here is what happens when we try to access a property called name. Remember that there isn't really a $name property declared, though you'd never know that without seeing the internal class code.

1
$device->user = 'Steve';
2
echo $device->user;
3
// Steve

We have set and successfully retrieved the value of a nonexistent property. Well where is it stored then?

1
print_r($device->data);
2
/*

3
Array

4
(

5
    [user] => Steve

6
)

7
*/

As you can see, the $data property now contains a 'name' element with our value.

1
var_dump(isset($device->user));
2
// bool(true)

Above is the result of calling isset() on the fake property.

1
unset($device->user);
2
var_dump(isset($device->user));
3
// bool(false)

Above is the result of unsetting the fake property. Just to make sure, here is our empty data array:

1
print_r($device->data);
2
/*

3
Array

4
(

5
)

6
*/

Representing Objects As Text

Sometimes you might want to convert an object to a string representation. If you simply try to print an object we'll get an error, such as the one below:

1
$device = new Device(new Battery(), 'iMagic');
2
echo $device;
3
// Result : PHP Catchable fatal error:  Object of class Device could not be converted to string

__toString()

The __toString() method is called when code attempts to treat an object like a string. It accepts no arguments and should return a string. This allows us to define how the object will be represented. In our example, we'll create a simple summary:

1
class Device {
2
    ...
3
    public function  __toString() {
4
        // are we connected?

5
        $connected = (isset($this->connection)) ? 'connected' : 'disconnected';
6
        // how much data do we have?

7
        $count = count($this->data);
8
        // put it all together

9
        return $this->name . ' is ' . $connected . ' with ' . $count . ' items in memory' . PHP_EOL;
10
    }
11
    ...
12
}

With the above method defined, here is what happens when we try to print a Device object:

1
$device = new Device(new Battery(), 'iMagic');
2
echo $device;
3
// iMagic is connected with 0 items in memory

The Device object is now represented by a short summary containing the name, status, and number of stored items.

__set_state() (PHP 5.1)

The static __set_state() method (available as of PHP version 5.1) is called when the var_export() function is called on our object. The var_export() function is used to convert a variable to PHP code. This method accepts an associative array containing the property values of the object. For simplicity's sake, well use it in our Battery class.

1
class Battery {
2
    //...

3
    public static function  __set_state(array $array) {
4
        $obj = new self();
5
        $obj->setCharge($array['charge']);
6
        return $obj;
7
    }
8
    //...

9
}

Our method simply creates an instance of its parent class and sets to charge to the value in the passed array. With the above method defined, here is what happens when we use var_export() on a Device object:

1
$device = new Device(new Battery(), 'iMagic');
2
var_export($device->battery);
3
/*

4
Battery::__set_state(array(

5
   'charge' => 0,

6
))

7
*/
8
eval('$battery = ' . var_export($device->battery, true) . ';');
9
var_dump($battery);
10
/*

11
object(Battery)#3 (1) {

12
  ["charge:private"]=>

13
  int(0)

14
}

15
*/

The first comment shows what is actually happening, which is that var_export() simply calls Battery::__set_state(). The second comment shows us successfully recreating the Battery.


Cloning Objects

Objects, by default, are passed around by reference. So assigning other variables to an object will not actually copy the object, it will simply create a new reference to the same object. In order to truly copy an object, we must use the clone keyword.

This 'pass by reference' policy also applies to objects within objects. Even if we clone an object, any child objects it happens to contain will not be cloned. So we would end up with two objects that share the same child object. Here's an example that illustrates that:

1
$device = new Device(new Battery(), 'iMagic');
2
$device2 = clone $device;
3
4
$device->battery->setCharge(65);
5
echo $device2->battery->charge;
6
// 65

Here, we have cloned a Device object. Remember that all Device objects contain a Battery object. To demonstrate that both clones of the Device share the same Battery, the change we made to $device's Battery is reflected in $device2's Battery.

__clone()

The __clone() method can be used to solve this problem. It is called on the copy of a cloned object after cloning takes place. This is where you can clone any child objects.

1
class Device {
2
    ...
3
    public function  __clone() {
4
        // copy our Battery object

5
        $this->battery = clone $this->battery;
6
    }
7
    ...
8
}

With this method declared, we can now be sure the cloned Devices each have their own Battery.

1
$device = new Device(new Battery(), 'iMagic');
2
$device2 = clone $device;
3
4
$device->battery->setCharge(65);
5
echo $device2->battery->charge;
6
// 0

Changes to one Device's Battery do not affect the other.


Object Serialization

Serialization is the process that converts any data into a string format. This can be used to store entire objects into a file or database. When you unserialize the stored data, you'll have the original object exactly as it was before. One problem with serialization, though, is that not everything can be serialized, such as database connections. Fortunately there are some magic methods that allow us to handle this problem.

__sleep()

The __sleep() method is called when the serialize() function is called on the object. It accepts no arguments and should return an array of all properties that should be serialized. You can also complete any pending tasks or cleanup that may be necessary in this method.

Tip: Avoid doing anything destructive in __sleep() since this will affect the live object, and you may not always be done with it.

In our Device example, the connection property represents an external resource that cannot be serialized. So our __sleep() method simply returns an array of all the properties except $connection.

1
class Device {
2
    public $name;           // the name of the device

3
    public $battery;        // holds a Battery object

4
    public $data = array(); // stores misc. data in an array

5
    public $connection;     // holds some connection resource

6
    //...

7
    public function  __sleep() {
8
        // list the properties to save

9
        return array('name', 'battery', 'data');
10
    }
11
    //...

12
}

Our __sleep() simply returns a list of the names of properties that should be preserved.

__wakeup()

The __wakeup() method is called when the unserialize() function is called on the stored object. It accepts no arguments and does not need to return anything. Use it to reestablish any database connection or resource that was lost in serialization.

In our Device example, we simply need to reestablish our connection by calling our connect() method.

1
class Device {
2
    //...

3
    public function  __wakeup() {
4
        // reconnect to the network

5
        $this->connect();
6
    }
7
    //...

8
}

Method Overloading

These last two methods are for dealing with methods. This is the same concept as the property overloading methods (__get(), __set(), etc), but applied to methods.

__call()

The __call() is called when code attempts to call inaccessible or nonexistent methods. It accepts two arguments: the name of the called method and an array of arguments. You can use this information to call the same method in a child object, for example.

In the examples, note the use of the call_user_func_array() function. This function allows us to dynamically call a named function (or method) with the arguments stored in an array. The first argument identifies the function to call. In the case of naming methods, the first argument is an array containing a class name or object instance and the name of the property. The second argument is always an indexed array of arguments to pass.

In our example, we'll be passing the method call to our $connection property (which we assume is an object). We'll return the result of that straight back to the calling code.

1
class Device {
2
    //...

3
    public function  __call($name, $arguments) {
4
        // make sure our child object has this method

5
        if(method_exists($this->connection, $name)) {
6
            // forward the call to our child object

7
            return call_user_func_array(array($this->connection, $name), $arguments);
8
        }
9
        return null;
10
    }
11
    //...

12
}

The above method would be called if we try to call the iDontExist() method:

1
$device = new Device(new Battery(), 'iMagic');
2
$device->iDontExist();
3
// __call() forwards this to $device->connection->iDontExist()

__callStatic() (PHP 5.3)

The __callStatic() (available as of PHP version 5.3) is identical to __call() except that it is called when code attempts to call inaccessible or nonexistent methods in a static context.

The only differences in our example is that we declare the method as static and we reference a class name instead of an object.

1
class Device {
2
    //...

3
    public static function  __callStatic($name, $arguments) {
4
        // make sure our class has this method

5
        if(method_exists('Connection', $name)) {
6
            // forward the static call to our class

7
            return call_user_func_array(array('Connection', $name), $arguments);
8
        }
9
        return null;
10
    }
11
    //...

12
}

The above method would be called if we try to call the static iDontExist() method:

1
Device::iDontExist();
2
// __callStatic() forwards this to Connection::iDontExist()

Using Objects As Functions

Sometimes you might want to use an object as a function. Being able to use an object as a function allows you to pass functions around as arguments like you can in other languages.

__invoke() (PHP 5.3)

The __invoke() (available as of PHP version 5.3) is called when code tries to use the object as a function. Any arguments defined in this method will be used as the function arguments. In our example, we'll simply be printing the argument that it receives.

1
class Device {
2
    //...

3
    public function __invoke($data) {
4
        echo $data;
5
    }
6
    //...

7
}

With the above defined, this is what happens when we use a Device as a function:

1
$device = new Device(new Battery(), 'iMagic');
2
$device('test');
3
// equiv to $device->__invoke('test')

4
// Outputs: test

Bonus: __autoload()

This is not a magic method, but it is still very useful. The __autoload() function is automatically called when a class that doesn't exist is referenced. It is meant to give you one last chance to load the file containing the class declaration before your script fails. This is useful since you don't always want to load every class just in case you need it.

The function accepts one argument: the name of the referenced class. Say you have each class in a file named 'classname.class.php' in the 'inc' directory. Here is what your autoload would look like:

1
function __autoload($class_name) {
2
    $class_name = strtolower($class_name);
3
    include_once './inc/' . $class_name . '.class.php';
4
}

Conclusion

Magic methods are extremely useful and provide powerful tools for developing flexible application frameworks. They bring PHP objects closer to those in other object oriented languages by allowing you to reproduce some of their more useful features. You can read the PHP manual pages on magic methods here. I hope this tutorial was helpful and clearly explained the concepts. If you have any questions, don't hesitate to ask in the comments. Thanks for reading.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.