PHP is a dynamically typed language, meaning variables do not need predefined types during script execution, and functions can lack parameter types or return types. PHP overloading refers to the dynamic creation or modification of class properties and methods during runtime.
PHP supports two main types of overloading:
1. Property overloading: Magic methods __get() and __set() allow dynamic access and modification of class properties.
2. Method overloading: Magic methods __call() and __callStatic() enable dynamic method invocation.
When accessing a non-existent property, the __get() method is called. This magic method allows dynamic addition of properties.
class Test {
private $data = [
'name' => 'Tom',
'age' => 18
];
public function __get($name) {
if (isset($this->data[$name])) {
return $this->data[$name];
}
return null;
}
}
$test = new Test();
echo $test->name; // Output Tom
echo $test->age; // Output 18
echo $test->gender; // Output null
The __get() method accepts one parameter, $name, which is the property name. If the property doesn't exist, it returns null.
When assigning a value to a non-existent property, the __set() method is triggered. This magic method allows dynamic addition of both properties and their values.
class Test {
private $data = [];
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$test = new Test();
$test->name = 'Tom';
echo $test->name; // Output Tom
The __set() method accepts two parameters: $name (the property name) and $value (the property value).
When calling a non-existent method, the __call() method is invoked. This magic method allows dynamic method creation.
class Test {
public function __call($name, $arguments) {
if ($name == 'add') {
return array_sum($arguments);
}
return null;
}
}
$test = new Test();
echo $test->add(1, 2, 3); // Output 6
echo $test->subtract(10, 2); // Output null
The __call() method accepts two parameters: $name (the method name) and $arguments (the method arguments). If the method does not exist, it returns null.
When calling a non-existent static method, the __callStatic() method is invoked. This method is similar to __call(), but is used for static methods.
class Test {
public static function __callStatic($name, $arguments) {
if ($name == 'add') {
return array_sum($arguments);
}
return null;
}
}
echo Test::add(1, 2, 3); // Output 6
echo Test::subtract(10, 2); // Output null
The __callStatic() method is similar to __call(), but it is only used for static methods.