Home > Backend Development > PHP Tutorial > Correctly understand PHP overloading

Correctly understand PHP overloading

藏色散人
Release: 2023-04-07 17:40:01
forward
2101 people have browsed it

PHP overloading is different from Java overloading and cannot be confused. 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 of PHP refers to the dynamic creation of attributes and classes through magic methods

● Overloading of attributes-__get and __set

● Overloading of methods- __call and __callStatic

For example, Laravel's request class implements attribute overloading, making the code more concise

$name = $request->name;
Copy after login

This attribute does not exist in the class, but is passed through the magic method To visit, the specific implementation is as follows

public function __get($key)
{
    return Arr::get($this->all(), $key, function () use ($key) {
        return $this->route($key);
    });
}
Copy after login

This implementation method is widely used, and the principle of implementation is simply summarized

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]);
    }
}
Copy after login

The above is the detailed content of Correctly understand PHP overloading. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template