Home  >  Article  >  Backend Development  >  Correctly understand PHP overloading

Correctly understand PHP overloading

藏色散人
藏色散人forward
2019-10-23 13:24:332037browse

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;

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);
    });
}

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

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

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete
Previous article:anonymous functionNext article:anonymous function