Zend PHP 7 Certification – OOP – Magic Methods

This post covers the Magic Methods section of the OOP chapter when studying for the Zend PHP 7 Certification.

Magic methods in PHP are methods that allow you to react to certain events when using objects. They are usually prefixed with a double underscore, __.

Some of the methods are what PHP defines as ‘magical’ can be seen below.

  • __construct()
  • __destruct()
  • __call()
  • __callStatic()
  • __get()
  • __set()
  • __isset()
  • __unset()
  • __sleep()
  • __wakeup()
  • __toString()
  • __invoke()
  • __clone()

The __construct() method is used to define constructors.

<?php
class Person {
    public $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

$person = new Person("John");
echo $person->name;

__destruct() in PHP is called when the object is destroyed, which is handled by the Garbage Collector which keeps an eye on your objects and automatically destroys them when they are no longer needed.

Use the __destruct() method to close specific resources.

<?php
class MyDestructableClass {
    function __construct() {
        print "In constructor\n";
        $this->name = "MyDestructableClass";
    }

    function __destruct() {
        print "Destroying " . $this->name . "\n";
    }
}

$obj = new MyDestructableClass();

// Outputs:
In constructor
Destroying MyDestructableClass

The __call() method is triggered when invoking inaccessible methods in an object context. If a class implements __call(), then if an object of that class is called with a method that doesn’t exist __call() is called instead.

<?php
class MyClass {
    public function __call($method, $args) {
        echo "Non existent method $method";
    }
}

$class = new MyClass();
$class->someNonExistentMethod(); // Outputs: Non existent method someNonExistentMethod!

Similar to __call(), __callStatic() is triggered when invoking inaccessible methods in a static context.

<?php
class MyClass {
    public function __callStatic($method, $args) {
        echo "Non existent static method $method";
    }
}

MyClass::someNonExistentStaticMethod(); // Outputs: Non existent static method

__get() is utilised for reading data from inaccessible properties.

<?php
class MyClass {
    public function __get($property) {
        echo "Non existent property $property";
    }
}

$class = new MyClass();
$class->someProp; // Outputs: Non existent property someProp

__set() is run when writing data to inaccessible properties.

<?php
class MyClass {
    public function __set($property, $value) {
        echo "Can't set '$value' to non existent property $property";
    }
}

$class = new MyClass();
$class->someProp = "Some value"; // Outputs: Can't set 'Some value' to non existent property someProp

The __isset() method is triggered by calling the isset() or empty() functions on inaccessible properties.

class MyClass {
    public function __isset($property) {
        echo "Nope. $property does not exist";
    }
}

$class = new MyClass();
isset($class->someProp); // Outputs: Nope. someProp does not exist

Likewise, __unset() is triggered by calling unset() on inaccessible properties.

class MyClass {
    public function __unset($property) {
        echo "Nope. $property does not exist";
    }
}

$class = new MyClass();
unset($class->someProp); // Outputs: Nope. someProp does not exist

The serialize() function checks if your class has a function with the __sleep() magic method.

If so, that function is executed prior to any serialisation. The __sleep() method returns an array with the names of all variables of that object that should be serialised.

<?php
class MyClass {
    public $someProperty = "Some Value";
    
    public function __sleep() {
        return array("someProperty");
    }
}

$class = new MyClass();
serialize($class);

Therefore the intended use of __wakeup() is to reestablish any database connections that may have been lost during serialisation and perform other reinitialisation tasks.

The unserialize() function checks for the presence of a function with the __wakeup() magic method.

<?php
class MyClass {
    public function __wakeup() {
        echo "Some re-connection details here";
    }
}

$class = new MyClass();
$str = serialize($class);
unserialize($str); // Outputs: Some re-connection details here

The __toString() method allows a class to decide how it will react when it is treated like a string. The method must return a string.

<?php
class MyClass {
    public $property = "Hello";

    public function __toString() {
        return $this->property;
    }
}

$class = new MyClass();
echo $class; // Outputs: Hello

__invoke() is called when a script tries to call an object as a function.

<?php
class MyClass {

    public function __invoke($x) {
        echo "Within " . __METHOD__;
    }
}

$class = new MyClass();
$class(5); // Outputs: Within MyClass::__invoke

An object copy is created by using the clone keyword, which calls the object’s __clone() method if available. This method allows any necessary properties that need to be changed.

<?php
class MyClass {
    public $someNo = 1;

    public function __clone() {
        return $this->someNo++;
    }
}

$class = new MyClass();
echo $class->someNo . "\n";

$clonedClass = clone $class;
echo $clonedClass->someNo;

// Outputs:
1
2

View the other sections:

Note: This article is based on PHP version 7.0.