We know that PHP overloading is different from Java overloading. Java allows multiple functions with the same name in a class, and each function has different parameters, while PHP only allows one function with the same name. For example, Java can have multiple constructors, but PHP can only have one constructor.
Overloading in PHP refers to the dynamic creation of properties and classes through magic methods.
1. Overloading of attributes: __get and __set
2. Overloading of methods: __call and __callStatic
(Online learning video sharing: php Video tutorial)
For example: Laravel's request class implements attribute overloading, making the code more concise
$name = $request->name;
This attribute does not exist in the class, but is passed through Magic method to access, the specific implementation is as follows:
public function __get($key) { return Arr::get($this->all(), $key, function () use ($key) { return $this->route($key); }); }
This implementation method is widely used, for example, the principle of inductive implementation:
class Foo { private $params = []; function __construct(array $params = []) { $this->params = $params; } public function __set($name, $value) { $this->params[$name] = $value; } public function __get($name) { return $this->params[$name]; } public function __isset($name) { return isset($this->params[$name]); } public function __unset($name) { unset($this->params[$name]); } }
Recommended related article tutorials: php tutorial
The above is the detailed content of How to understand php reloading. For more information, please follow other related articles on the PHP Chinese website!