Overloading of PHP - implemented by magic method

Excerpt from the explanation of PHP overload on PHP official website:


The "overloading" provided by PHP refers to dynamically "creating" class properties and methods. We implement it through magic methods.
When a class property or method that is not defined or visible in the current environment is called, the overloaded method will be called. Later in this section, "inaccessible properties" and "inaccessible methods" will be used to address these undefined or invisible class properties or methods.
All overloaded methods must be declared public.

Note:
The parameters of these magic methods cannot be passed by reference.

Note:
The "overloading" in PHP is different from most other object-oriented languages. The traditional "overloading" is used to provide multiple class methods with the same name, but the parameter types and number of each method are different.

Property Override
public __set ( string $name , mixed $value ) : void
public __get ( string $name ) : mixed
public __isset ( string $name ) : bool
public __unset ( string $name ) : void

When assigning a value to an inaccessible property__ set() will be called.
When reading the value of an inaccessible property__ get() will be called.
When isset() or empty() is called on an inaccessible property__ Isset () will be called.
When unset() is called on an inaccessible property__ Unset() will be called.
Parameter $name refers to the name of the variable to be operated__ The $value parameter of the set() method specifies the value of the $name variable.
Property overloading can only be done in objects. In static methods, these magic methods will not be called. Therefore, none of these methods can be declared as static.

Note:
Because of the way PHP handles assignment operations__ The return value of set() will be ignored. Similarly, in the following chain assignment__ get() will not be called:
$a = $obj->b = 8;

Note:
Overloaded properties cannot be used in language structures other than isset(), which means that when empty() is used on an overloaded property, the overloaded magic method will not be called.
To avoid this limitation, you must assign the overloaded attribute to a local variable and then use empty().

Example #1 use__ get(),__ set(),__ isset() and__ unset() for property overloading

class PropertyTest
{
    /**  The overloaded data is saved here  */
    private $data = array();

    /**  Overloads cannot be used on defined properties  */
    public $declared = 1;

    /**  Overloading occurs only when this property is accessed from outside the class */
    private $hidden = 2;

    public function __set ($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function __get ($name)
    {
        if (isset($this->$name)) {
            return $this->$name;
        }
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }
        //Generate a backtrace
        $trace = debug_backtrace();
        //Throw exception
        trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE);
        return null;
    }

    public function __isset ($name)
    {
        return isset($this->data[$name]);
    }

    public function __unset ($name)
    {
        unset($this->data[$name]);
    }

    /**  Non magic method  */
    public function getHidden ()
    {
        return $this->hidden;
    }
}

$obj = new PropertyTest;

//Output the non-existent a variable, go to__ In get(), an exception will be thrown
echo $obj->a;

//Assign a value of 1 to the nonexistent a variable, and you will go to__ In set()
$obj->a = 1;

//Output the a variable again, because it has been modified above__ set(), so it is possible to access the value of a, which is 1
echo $obj->a;

//At this time, when using isset () to operate on the nonexistent a variable, you will go to__ isset(), because it has been__ set(), so it is true
var_dump(isset($obj->a));

//When you unset () a, you will go to__ In unset()
unset($obj->a);

//Then isset it (), which no longer exists
var_dump(isset($obj->a));

//Accessing the variable of private attribute will enter__ In get()
echo $obj->hidden;

Method overloading
public __call ( string $name , array $arguments ) : mixed
public static __callStatic ( string $name , array $arguments ) : mixed

When an invocation method is invoked in an object, call() will be called.
When an invocation method is invoked in a static context, callStatic() will be called.
The $name parameter is the name of the method to be called.
The $arguments parameter is an enumerated array containing the parameters to be passed to the method $name.

Example #2 use__ call() and__ callStatic() overloads the method

class MethodTest
{
    /**
     * Enter here when calling a method that does not exist
     * @param $name
     * @param $arguments
     */
    public function __call ($name, $arguments)
    {
        // Note: the value of $name is case sensitive
        $info = [
            'name' => $name,
            'arguments' => $arguments,
        ];
        print_r($info);
    }

    /**
     * PHP 5.3.0 Later version
     * Enter here when calling a static method that does not exist
     */
    public static function __callStatic ($name, $arguments)
    {
        // Note: the value of $name is case sensitive
        $info = [
            'name' => $name,
            'arguments' => $arguments,
        ];
        print_r($info);
    }
}

$arguments = ['A', 'B', 'C'];

$obj = new MethodTest;
$obj->test(...$arguments);

MethodTest::test(...$arguments);  // PHP version after 5.3.0

/*
 *  Both outputs:
 *  Array
    (
        [name] => test
        [arguments] => Array
            (
                [0] => A
                [1] => B
                [2] => C
            )

    )
 */

The above contents would like to help you, more PHP PDF interview documents, PHP advanced architecture video data, PHP wonderful and good free access to WeChat search official account: PHP open source community, or visit:

2021 gold, silver and four major factories interview true questions collection, must see!

Four years essence PHP technical articles collation Collection - PHP framework article

Four years essence PHP technology collection - micro service architecture chapter

Four years essence PHP technology collection - distributed architecture chapter

Four years essence PHP technology collection - high concurrency scenario

Four years essence PHP technical articles collation Collection - database articles

Added by nikhar021 on Fri, 04 Mar 2022 03:04:52 +0200