PHP Magic Methods
Magic methods are special methods which override PHP's default's action when certain actions are performed on an object. They always start with two underscores __.
1. __toString()
The __toString() method allows a class to decide how it will react when it is treated like a string.
class Bird {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function __toString() {
return "This bird is a " . $this->name;
}
}
$bird = new Bird("Canary");
echo $bird; // Outputs: This bird is a Canary
2. get() and set()
These methods are used for property overloading.
__set()is run when writing data to inaccessible (protected or private) or non-existing properties.__get()is utilized for reading data from inaccessible (protected or private) or non-existing properties.
class User {
private $data = array();
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
return $this->data[$name];
}
}
$user = new User();
$user->username = "JohnDoe"; // Calls __set
echo $user->username; // Calls __get
3. Other Common Magic Methods
__call($name, $args): Triggered when invoking inaccessible methods.__isset($name): Triggered by callingisset()orempty()on inaccessible properties.__unset($name): Triggered by callingunset()on inaccessible properties.__invoke(): Called when a script tries to call an object as a function.