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 Method | Description |
---|---|
__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 ) : void
Code 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:
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 = "tag>"; foreach ($this->attributes as $key => $value) < $html .= ' ' . $key . ' hljs-string">'"'; > $html .= '>'; $html .= $innerHTML; $html .= "$this->tag>"; return $html; > >
Code language: HTML, XML (xml)
- 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:
require 'HTMLElement.php'; $div = new HtmlElement('div'); $div->id = 'page'; $div->class = 'light'; echo $div->html('Hello');
Code language: HTML, XML (xml)
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 ) : mixed
Code language: PHP (php)
The following adds the __get() method to the HTMLElement class:
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 = "tag>"; foreach ($this->attributes as $key => $value) < $html .= ' ' . $key . ' hljs-string">'"'; > $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:
require 'HTMLElement.php'; $article = new HtmlElement('article'); $article->id = 'main'; $article->class = 'light'; // show the attributes echo $article->class; // light echo $article->id; // main
Code language: HTML, XML (xml)
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.
How to Use the PHP __get and __set Magic Methods
In this article, we show how to use the PHP __get and __set magic methods.
The PHP __get and __set magic methods function as getters and setters for object values, but it had the added advantage in that you don’t have to declare the object properties (variables) in the class.
Instead when you set a value (with the object property never declared in the class), the __set magic method is automatically called and sets the value.
The same is true for the __get method. Without the object property being declared in the class that you want to get, the __get magic method is automatically called and gets the value.
So the __get and __set magic methods function as getters and setters, without the object property variable having to be declared in the class.
We will show each of these in the code below.
In the code below, we make a class called kids. In this class, we set a child’s height through the __set method or get a child’s height through the __get method.
Getter and setter methods provide encapsulation of data so that in order to set or get data, it has to pass through a method. The reason we do this is because many times we want to test the data first to make sure that’s an appropriate or reasonable value.
In this class, we are setting the height of a kid. For example, the height cannot be negative. The height can’t be 1 inch tall. No child is one inch tall. This is the reason we only allow for heights 30 inches or grader. Imagine this is fifth grade student. They all are way past this point.
So passing data first through a method allows us to filter out bad data. It allows for this encapsulation where we don’t have to accept bad data, such as a negative height or 0.5 inches tall.
This is why getter and setter methods are commonly used.
So we create a class called kids.
Inside of this class we create the setter and getter methods.
The first method that we create the setter method using the __set function. The setter function has to accept 2 parameters, the object property you are defining and the value of this object property. As we are setting a child’s height in this code, the height is the object property and the value of the height we set it to is the value. We make it so that if the value passed into the object property is greater than 30, we set the object property to that value. If the value is less than 30, then the magic set method does not set the value.
We then create the next function, the getter method using the __get function. The get function accepts one parameter, the $property of the object. We do not need the $value as the parameter, because the $value is already set by the setter function. With the getter function, we do not set the value. We just retrieve the value that’s already been set. So in this getter function, we return the child’s height in inches by calling the $this->property function. $this->property refers to the value of the property of the object we’re getting.
All of this will make more sense now below.
So underneath this, we create an object of the kids class, $kid1.
We then the object property, height, of $kid1 equal to 45. This makes the kid’s height 45 inches.
What’a amazing about the magic method __set() in PHP is that we have defined the property variable $height anywhere in the class. Yet we’re just automatically setting the height of the $kid1 object. This triggers the PHP __set() magic method. The method sees the height as a property of the object and 45 as the value of this height property. $kid1 is the object of this call.
So because we automatically set an object property and its height without declaring them or calling a function, this automatically calls the PHP __set() magic method. So the $property value is height. The $value of this property is 45. We set the value only if the value is greater than 30. We set the value through the line, $this->property= $value. $this refers to the object kid1. We set $kid->height= 45. So now you can see how this is set through the PHP __set magic method.
To automatically get the property of an object, you call an output function such as echo or print with the parameter of an object and property. This automatically triggers the PHP __get magic method.
The only parameter needed for the __get() method is the $property variable. We return out what the child’s height is in inches.
So this is all that is required to use the PHP __get and __set magic methods. It’s very adaptable because you don’t need to declare variables in the class and you don’t need to call a function. If you set it up properly, like how demonstrated, it will automatically call the __get or __set magic methods. So in this way, it simplifies code.
Running the PHP code above yields the following output shown below.
Actual PHP Output
The child’s height is 45 inches tall