"Magic methods" in PHP are unique methods that begin with a double underscore (__) and are used to handle certain actions or behaviors within a class. These methods are called by PHP at specified times and are intended to provide a means to do common tasks without explicitly using them in your code.
Here are some examples of regularly used magic procedures in PHP:
__construct(): When a class object is formed, this magic function is automatically invoked. It is employed in initialization chores.
Pass the DateTimeZone object to a new Date Time object. This function returns the current time in the specified time zone.
Here's some code to show you how:
class MyClass {
public function __construct() {
echo "Object created! Initialization complete.";
}
}
$obj = new MyClass(); // Output: Object created! Initialization complete.
__destruct(): This magic method is automatically called when an object is no longer referenced or goes out of scope. It is used for cleanup tasks.
class MyClass {
public function __destruct() {
echo "Object destroyed! Cleanup complete.";
}
}
$obj = new MyClass(); // Object created!
// At the end of the script or when $obj goes out of scope, the destructor will be called.
__get() and __set(): These methods are used to intercept attempts to read (get) or write (set) inaccessible properties of an object.
class MyClass {
private $data = [];
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$obj = new MyClass();
$obj->name = "John"; // Calls __set() to set the value of 'name'.
echo $obj->name; // Calls __get() to retrieve the value of 'name'.
// Output: John
__call(): This method is invoked when calling inaccessible methods in the context of an object.
class MyClass {
public function __call($name, $arguments) {
echo "Calling method '$name' with arguments: " . implode(', ', $arguments);
}
}
$obj = new MyClass();
$obj->myMethod('arg1', 'arg2');
// Output: Calling method 'myMethod' with arguments: arg1, arg2
__toString(): This method is called when an object is treated as a string, for example, when using echo or print.
class MyClass {
public function __toString() {
return "This is MyClass";
}
}
$obj = new MyClass();
echo $obj; // Output: This is MyClass
These are just a few examples of magic methods in PHP. There are more magic methods like __isset(), __unset(), __clone(), etc., each serving specific purposes and allowing developers to customize the behavior of their classes.
Hope it can help your development.