PHP - Class Magic methods

Introduction

There are methods that have special meanings.

Those methods are called magic methods.

Constructor of the class, __construct, is one of them.

Magic methods start with __.

The following are some of the most used magic methods:

Method Description
__toString invoked when we try to cast an object to a string. It takes no parameters, and it is expected to return a string.
__callPHP calls it when you try to invoke a method on a class that does not exist. It gets the name of the method as a string and the list of parameters used in the invocation as an array, through the argument.
__getIt gets the name of the property that the user was trying to access through parameters, and it can return anything.

You could use the __toString method to output information about our Book class.

public function __toString() { 
    $result = '<i>' . $this->title . '</i> - ' . $this->author; 
    if (!$this->available) { 
        $result .= ' <b>Not available</b>'; 
    } 
    return $result; 
 } 

The following code creates an object book and then casts it to a string, invoking the __toString method:

$book = new Book(1234, 'title', 'author'); 
$string = (string) $book; // title - author Not available 

Related Topics

Exercise