Junior
What are magic methods in PHP?
sobes.tech AI
Answer from AI
Magic methods in PHP are special methods that are called automatically under certain circumstances. Their names start with two underscores (__).
List of main magic methods:
__construct(): Called when a new object is created.__destruct(): Called when an object is destroyed.__call($name, $arguments): Called when attempting to invoke an inaccessible or non-existent method of an object.__callStatic($name, $arguments): Called when attempting to invoke an inaccessible or non-existent static method.__get($name): Called when attempting to access an inaccessible property of an object.__set($name, $value): Called when attempting to set a value to an inaccessible property of an object.__isset($name): Called when usingisset()orempty()on an inaccessible property.__unset($name): Called when usingunset()on an inaccessible property.__sleep(): Called before serialization, returns an array of property names for serialization.__wakeup(): Called after deserialization.__toString(): Allows the object to behave as a string when used in a string context.__invoke($args): Called when the script tries to invoke the object as a function.__set_state(array $properties): Called when exporting an object withvar_export().__clone(): Called after cloning an object to set up the clone.__serialize(): Called during serialization, returns an array of data for serialization.__unserialize(array $data): Called during deserialization, receives data from__serialize().
Example of using __construct and __destruct:
<?php
class Example {
public function __construct() {
echo "Object created\n";
}
public function __destruct() {
echo "Object destroyed\n";
}
}
$obj = new Example();
unset($obj); // Forcibly destroys the object
?>
Example of using __get and __set:
<?php
class DataStore {
private $data = [];
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
return null; // Or throw an exception
}
}
$store = new DataStore();
$store->name = "Alice"; // Calls __set
echo $store->name; // Calls __get
?>