Junior
What are magic methods in PHP?
sobes.tech AI
Answer from AI
Magic methods in PHP are special methods whose names start with a double underscore (__). They are called automatically in certain situations or in response to specific actions with an object.
The most common magic methods:
__construct(): Called when a new object is created. Used for initializing object properties.__destruct(): Called when an object is destroyed or garbage collected. Used for cleanup or resource release.__call($name, $arguments): Called when attempting to invoke an inaccessible (private or non-existent) method of an object.__callStatic($name, $arguments): Called when attempting to invoke an inaccessible static method of a class.__get($name): Called when attempting to read an inaccessible (private or non-existent) property of an object.__set($name, $value): Called when attempting to write to an inaccessible (private or non-existent) property of an object.__isset($name): Called when checking the existence of an inaccessible property usingisset()orempty().__unset($name): Called when unsetting an inaccessible property usingunset().__sleep(): Allows the object to prepare for serialization. Must return an array of property names to serialize.__wakeup(): Called after an object is unserialized. Used to restore resources that may have been lost during serialization.__toString(): Allows the object to define how it should be represented as a string. Called when the object is used in a string context.__invoke(...): Called when the object is used as a function.__set_state(array $properties): Called when creating an object with thevar_export()function.__clone(): Called when the object is cloned using theclonekeyword. Used for setting up the cloned object.__debugInfo(): Customizes the debug output for the object when used with functions likevar_dump().
Example of using __get() and __set():
<?php
class Person {
private $data = [];
public function __set($name, $value) {
echo "Setting property '$name' to '$value'\n";
$this->data[$name] = $value;
}
public function __get($name) {
echo "Getting property '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
return null; // Or throw an exception
}
}
$person = new Person();
$person->name = "Alice"; // Calls __set()
echo $person->name; // Calls __get()
?>
Magic methods provide a mechanism to intercept and manage certain operations with objects, allowing for more flexible and dynamic classes. However, their excessive use can complicate code readability and debugging.