PHP magic methods are special methods that allow you to control the behavior of objects in PHP. These methods are automatically called in response to specific actions, enabling you to customize object behavior without directly calling a method. Some of the most common magic methods include:
__construct()
- Called when an object is created.__destruct()
- Called when an object is destroyed.__get()
- Called when accessing an inaccessible property.__set()
- Called when setting an inaccessible property.__call()
- Called when invoking inaccessible methods.__invoke()
- Called when an object is treated as a function.__toString()
- Called when an object is treated as a string.These methods provide a powerful way to manage object interactions, enforce encapsulation, and create more dynamic and flexible classes in PHP. Below is an example of how to use some of these magic methods:
class MagicExample {
private $data = [];
public function __construct($data) {
$this->data = $data;
}
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __toString() {
return implode(', ', $this->data);
}
}
$example = new MagicExample(['name' => 'John', 'age' => 30]);
echo $example->name; // Output: John
$example->city = 'New York';
echo $example; // Output: John, 30, New York
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?