PHP Magic Methods

Summary: in this tutorial, you will learn about PHP magic methods that override the default actions when the object performs the actions.

Introduction to PHP magic methods #

PHP magic methods are special methods in a class. The magic methods override the default actions when the object performs the actions.

By convention, the names of magic methods start with a double underscore (__). And PHP reserves the methods whose names start with a double underscore (__) for magic methods.

So far, you have learned that the constructor and destructor use the __construct() and __destruct() methods. In fact, the constructor and destructor are also magic methods.

The __construct() method is invoked automatically when an object is created and the __destruct() is called when the object is deleted.

Besides the __contruct() and __destruct() methods, PHP also has the following magic methods:

Magic MethodDescription
__call()is triggered when invoking an inaccessible instance method
__callStatic()is triggered when invoking an inaccessible static method
__get()is invoked when reading the value from a non-existing or inaccessible property
 __set()is invoked when writing a value to a non-existing or inaccessible property
 __isset()is triggered by calling isset() or empty() on a non-existing or inaccessible property
__unset()is invoked when unset() is used on a non-existing or inaccessible property.
__sleep()The __sleep() commits the pending data
__wakeup()is invoked when the unserialize() runs to reconstruct any resource that an object may have.
__serialize()The serialize() calls __serialize(), if available, and construct and return an associative array of key/value pairs that represent the serialized form of the object.
__unserialize()The unserialize() calls __unserialize(), if avaialble, and restore the properties of the object from the array returned by the __unserialize() method.
__toString()is invoked when an object of a class is treated as a string.
__invoke()is invoked when an object is called as a function
__set_state()is called for a class exported by var_export()
__clone()is called once the cloning is complete
__debugInfo()is called by var_dump() when dumping an object to get the properties that should be shown.

This tutorial will focus on the __set() and __get() methods.

PHP __set() method #

When you attempt to write to a non-existing or inaccessible property, PHP calls the __set() method automatically. The following shows the syntax of the __set() method:

public __set ( string $name , mixed $value ) : voidCode language: PHP (php)

The __set() method accepts the name and value of the property that you write to. The following example illustrates how to use the __set() method:

<?php

class HtmlElement
{
	private $attributes = [];

	private $tag;

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

	public function __set($name, $value)
	{
		$this->attributes[$name] = $value;
	}

	public function html($innerHTML = '')
	{
		$html = "<{$this->tag}";
		foreach ($this->attributes as $key => $value) {
			$html .= ' ' . $key . '="' . $value . '"';
		}
		$html .= '>';
		$html .= $innerHTML;
		$html .= "</$this->tag>";

		return $html;
	}
}Code language: HTML, XML (xml)

How it works.

  • First, define the HTMLElement class that has only one property $attributes. It will hold all the attributes of the HTML element e.g., id and class.
  • Second, initialize the constructor with a tag name. The tag name can be any string such as div, article, main, and section.
  • Third, implement the __set() method that adds any property to the $attribute array.
  • Fourth, define the html() method that returns the HTML representation of the element.

The following uses the HTMLElement class and create a new div element:

<?php

require 'HTMLElement.php';

$div = new HtmlElement('div');

$div->id = 'page';
$div->class = 'light';

echo $div->html('Hello');Code language: HTML, XML (xml)

Try it

Output:

<div id="page" class="light">Hello</div>Code language: HTML, XML (xml)

The following code attempts to write to the non-existing property:

$div->id = 'page';
$div->class = 'light';Code language: PHP (php)

PHP calls the __set() method implictily and adds these properties to the $attribute property.

PHP __get() method #

When you attempt to access a property that doesn’t exist or a property that is in-accessible e.g., private or protected property, PHP automatically calls the __get() method.

The __get() method accepts one argument which is the name of the property that you want to access:

public __get ( string $name ) : mixedCode language: PHP (php)

The following adds the __get() method to the HTMLElement class:

<?php

class HtmlElement
{
	private $attributes = [];

	private $tag;

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

	public function __set($name, $value)
	{
		$this->attributes[$name] = $value;
	}

	public function __get($name)
	{
		if (array_key_exists($name, $this->attributes)) {
			return $this->attributes[$name];
		}
	}

	public function html($innerHTML = '')
	{
		$html = "<{$this->tag}";
		foreach ($this->attributes as $key => $value) {
			$html .= ' ' . $key . '="' . $value . '"';
		}
		$html .= '>';
		$html .= $innerHTML;
		$html .= "</$this->tag>";

		return $html;
	}
}Code language: HTML, XML (xml)

The __get() method checks if the requested property exists in the $attributes before returning the result.

The following creates a new article element, sets the id and class attributes, and then shows the value of these attributes:

<?php

require 'HTMLElement.php';

$article = new HtmlElement('article');

$article->id = 'main';
$article->class = 'light';

// show the attributes
echo $article->class . '<br>'; // light
echo $article->id . '<br>'; // mainCode language: HTML, XML (xml)

Try it

Summary #

  • PHP Magic methods start with double underscores (__).
  • PHP calls the __get() method automatically when you access a non-existing or inaccessible property.
  • PHP calls the __set() method automatically when you assign a value to a non-existing or inaccessible property.
Did you find this tutorial useful?