PHP Magic Methods
Reserved methods, ships with special functionalities from the PHP end.
PHP Magic Functions
Constructor (__construct)
Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
Example
class Point {
protected int $x;
protected int $y;
public function __construct(int $x, int $y = 0) {
$this->x = $x;
$this->y = $y;
}
}
// Pass both parameters.
$p1 = new Point(4, 5);
// Pass only the required parameter. $y will take its default value of 0.
$p2 = new Point(4);
// With named parameters (as of PHP 8.0):
$p3 = new Point(y: 5, x: 4);
Destructor (__destruct)
The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
Example
class MyDestructableClass
{
function __construct() {
print "In constructor\n";
}
function __destruct() {
print "Destroying " . __CLASS__ . "\n";
}
}
$obj = new MyDestructableClass();
Property overloading
Setter (__set)
Method is run when writing data to inaccessible (protected or private) or non-existing properties
Getter (__get)
Method is utilized for reading data from inaccessible (protected or private) or non-existing properties.
IsSetter (__isset)
Method is triggered by calling isset() or empty() on inaccessible (protected or private) or non-existing properties.
UnSetter (__unset)
Method is invoked when unset() is used on inaccessible (protected or private) or non-existing properties.
Method overloading
Caller (__call)
Method is triggered when invoking inaccessible methods in an object context.
StaticCaller (__callStatic)
Method is triggered when invoking inaccessible methods in a static context.