Home  >  Article  >  Backend Development  >  Detailed explanation of PHP's magic methods __get(), __set(), __call(), __callStatic() and static usage

Detailed explanation of PHP's magic methods __get(), __set(), __call(), __callStatic() and static usage

伊谢尔伦
伊谢尔伦Original
2017-07-03 11:43:443191browse

After php5, I implemented some magic methods which is quite interesting. I have been using process-oriented programming methods before, and I have done relatively little research on oop. Recently, I have been looking at oop stuff, which is quite interesting.

It feels like a lot of magic methods are just for laziness. I remember when I first wrote PHP, when I was blogging, I used a foreign open source framework called lifetype. At that time, it was still PHP4. 3. But all objects are implemented in that framework, and all data are encapsulated into objects.

So after selecting a bunch of things from the db, they have to be encapsulated into objects one by one in a loop. Each field must also implement the getField() and getField() methods. It is really troublesome to write. It feels like Doing repetitive work.

The birth of these magic methods, get(), set(), call(), and callStatic(), has completely solved this problem.

get() and set() are for attributes in the class, call() is for methods, and callStatic() is for static class methods.

1. Get() and set() magic methods:

After instantiating an object, when calling attributes that do not exist in the class or do not have permission to access, PHP will The get() method is called by default. This not only saves a lot of code and makes the structure clearer, but also provides a method for external access to private members of the class.

For example:

<?php
class testGet
{
  private $name = &#39;test&#39;;
}
$test = new testGet();
$test->name;

If we run the above code, an error will be reported: PHP Fatal error: Cannot access private property testGet::$name in /Library/WebServer/ Documents/workspace/learn/call/a.php on line 7

But let’s modify it and access it through the get() method

<?php
class testGet
{
  private $name = &#39;test&#39;;

  function get($property) {
    if ( isset($this->$property) ) 
      return $this->$property;
    else
      return NULL;
  }
}
$test = new testGet();
echo $test->name . PHP_EOL;

After changing the code to this, we No problem if you visit again.

Note: If the attribute is defined as static, an error will also be reported when accessed through get(). The reason is that static members belong to the class itself and do not change due to instantiation, so you can test them yourself.

Using the set() method, you can prohibit the dynamic creation of class attributes, which can avoid unnecessary trouble for subsequent developers or program maintainers.

funciton set($property) {

//$property receives the name of the property

}

To be honest, the design of oop will be mixed with a lot of the designer’s own thoughts. If there is no documentation, it will still be very difficult for latecomers to read the code. Of course It also has a lot to do with the level of latecomers.

The following is an example of using get and set together:

<?php
class testGet
{
  private $name = &#39;test&#39;;

  function get($property) {
    if ( isset($this->$property) ) 
      return $this->$property;
    else
      return NULL;
  }
  
  public function set($property, $value) {
    if ( isset($this->$property) )
      $this->$property = $value;
    else
      return NULL;
  }
}
$test = new testGet();
$test->name = &#39;my test name&#39;;
echo $test->name . PHP_EOL;

function set($property, $value) {

/ /$property receives the name of the property

//$value receives the value of the property

}

2. call() and callStatic() methods:

When the object calls a method in the class that does not exist or does not have permission to access, the call() method will be automatically called.

I remember a colleague asked me before, why there are many low-level methods in the TP framework that are not available, but can still be called in the upper layer. In fact, it is the call() method that works.

If you don’t know this method, you will definitely be confused, and the problem will not be easy to locate.

<?php
abstract class Obj 
{
        private $objData        = array();
        /** 
         * call魔术方法,如果对象请求的方法不存在或者没有权限访问的时候
         * 调用魔术方法
         */
        public function call($name, $args) {
            $field = preg_match(&#39;/^get(\w+)/&#39;, $name, $matches);
            if ( $field && $matches[1] )
                return $this->objData[strtolower($matches[1])];
            $field = preg_match(&#39;/^set(\w+)/&#39;, $name, $matches);
            if ( $field && $matches[1] ) { 
                return $this->objData[strtolower($matches[1])] = $args[0];
            }   
        }   
}
class User extends Obj
{
        
}
$user = new User();
$user->setName(&#39;test&#39;);
echo $user->getName();

The User class does nothing, but does everything (getName and setName) through the call() method of the inherited class.

function call($methodName, $args) {

//The method name called by $methodName

//Parameters passed by $argsArray

}

and call() correspond to callStatic() Methods serve static methods of static classes.

Example:

<?php
    abstract class Obj 
    {
        private static $objData        = array();
        /** 
         * call魔术方法,如果对象请求的方法不存在或者没有权限访问的时候
         * 调用魔术方法
         */
        public static function callStatic($name, $args) {
            $field = preg_match(&#39;/^get(\w+)/&#39;, $name, $matches);
            if ( $field && $matches[1] )
                return self::$objData[strtolower($matches[1])];
            $field = preg_match(&#39;/^set(\w+)/&#39;, $name, $matches);
            if ( $field && $matches[1] ) { 
                return self::$objData[strtolower($matches[1])] = $args[0];
            }   
        }   
    }
    class User extends Obj 
    {
    
    }
    User::setName(&#39;test&#39;);
    echo User::getName() . PHP_EOL;

3. Delayed static binding: static object

The above is the detailed content of Detailed explanation of PHP's magic methods __get(), __set(), __call(), __callStatic() and static usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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