PHP __get and __set magic methods
The __get
and __set
magic methods in PHP are used to intercept calls to get or set the value of inaccessible properties of an object. They allow you to define custom behaviors when getting or setting the value of a property that is not directly accessible.
Here is an example of how you can use the __get
and __set
magic methods:
<?php
class MyClass
{
private $data = [];
public function __get($name)
{
// This magic method is called when a non-existent or inaccessible property is accessed.
// The parameter $name contains the name of the property that was accessed.
// The `array_key_exists()` function checks if the specified key exists in the array.
// In this case, it checks if the property with the name specified in $name exists in the $data array.
if (array_key_exists($name, $this->data)) {
// If the property exists in the $data array, return its value.
return $this->data[$name];
}
}
public function __set($name, $value)
{
// This magic method is called when a non-existent or inaccessible property is set.
// The parameter $name contains the name of the property that was set, and $value contains its value.
// The value of the property is stored in the $data array with the property name as the key.
$this->data[$name] = $value;
}
}
$obj = new MyClass();
$obj->foo = 'bar'; // Calls the __set() magic method, setting the 'foo' property to the value 'bar'.
echo $obj->foo; // Calls the __get() magic method, retrieving the value of the 'foo' property and outputting it.
In this code, a new class MyClass
is defined that has two magic methods, __get()
and __set()
. These methods are called when a property is accessed or modified that does not exist or is not accessible in the usual way.
In this case, the __get()
method is called when a property is accessed, and it checks if the property with the specified name exists in the $data
array. If it does, the method returns the value of that property.
The __set()
method is called when a property is modified, and it stores the new value of the property in the $data
array with the property name as the key.
In the example code, a new instance of MyClass
is created, and the foo
property is set to the value 'bar'
using the ->
operator, which calls the __set()
method to set the value. The value of the foo
property is then output using the echo
statement, which calls the __get()
method to retrieve the value of the property.
When the code is run, it outputs the string "bar"
, which is the value of the foo
property that was set earlier.
You can also use the __isset
and __unset
magic methods to intercept calls to the isset
and unset
functions, respectively. These magic methods allow you to define custom behavior when checking if a property is set or unsetting a property.