Home  >  Article  >  Backend Development  >  Introduction to php magic methods

Introduction to php magic methods

WJ
WJforward
2020-06-06 17:54:482266browse

Introduction to php magic methods

The previous words

PHP has many related magic methods in the object-oriented part. These methods provide convenience for object-oriented implementation. This article will introduce the magic methods in detail

Constructor method

Most classes have a special method called a constructor. When an object is created, it will automatically call the constructor, which is usually used to perform some useful initialization tasks

The declaration of the constructor is the same as the declaration of other operations, except that its name must be two underscores __construct( ). This is a change in PHP5; in the PHP4 version, the name of the constructor must be the same as the class name. For backward compatibility, if there is no method named __construct() in a class, PHP will search for a method with the same name as the class

void __construct ([ mixed $args [, $... ]] )

If a constructor is defined in a subclass, it will not be called implicitly The constructor of its parent class. To execute the constructor of the parent class, you need to call parent::__construct() in the constructor of the subclass. If the subclass does not define a constructor, it will be inherited from the parent class like an ordinary class method (if it is not defined as private)

<?phpclass BaseClass {
   function __construct() {
       print "In BaseClass constructor
";
   }
}class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();       print "In SubClass constructor
";
   }
}

Destructor method

The opposite of the construction method is the destruction method. The destructor method is a newly added content of PHP5. There is no destructor method in PHP4. The destructor method is a method that is automatically called before the object is destroyed. It mainly performs some specific operations, such as closing files, releasing result sets, etc.

Similar to the constructor method, the name of the destructor method of a class must be two underscore__destruct(). The destructor cannot take any parameters

<?phpclass MyDestructableClass {
   function __construct() {
       print "In constructor
";       $this->name = "MyDestructableClass";
   }   function __destruct() {
       print "Destroying " . $this->name . "
";
   }
}//In constructor Destroying MyDestructableClass$obj = new MyDestructableClass();?>

Inaccessible properties

get()

Read inaccessible properties (protected, private), __get() will be called, and the attribute name will be passed into this method as the first parameter (string)

public mixed __get ( string $name )

<?phpclass demo{
    protected $protected = 1;    public $public = 2;    private $private = 3;    function __get($name){
        echo "111{$name}111<br>";
    }
}$d1 = new demo;$d1->protected;//111protected111$d1->public;$d1->private;//111private111?>

set()

When assigning a value to an inaccessible property (protected, private), __set() will be called and the property name will be Pass the first parameter (string) and the value as the second parameter (mixed) into this method

public void __set ( string $name , mixed $value )
<?phpclass demo{
    protected $protected = 1;    public $public = 2;    private $private = 3;    function __set($name,$value){
        echo "0{$name}0{$value}<br>";
    }
}

isset()

When dealing with inaccessible properties ( protected, private) when calling isset() or empty(), __isset() will be called

public bool __isset ( string $name )
<?phpclass demo{
    protected $protected = 1;    public $public = 2;    private $private = 3;    function __isset($name){
        echo "0{$name}0<br>";
    }
}

unset()

 When the inaccessible property (protected, private) calls unset(), __unset() will be called

public void __unset ( string $name )

<?phpclass demo{
    protected $protected = 1;    public $public = 2;    private $private = 3;    function __unset($name){
        echo "0{$name}0<br>";
    }
}

Object copy

clone()

The clone() method is automatically called when an object is cloned. This method does not require any parameters and can be used to reinitialize the cloned copy

The clone() method will automatically include references to the two objects this and that. This is a reference to the copy object, and that is a reference to the original object

<?php
    class Person{
        private $name;        private $sex;        private $age;        function __construct($name="",$sex="",$age=1){
            $this->name= $name;            $this->sex = $sex;            $this->age = $age;
        }        function __clone(){
            $this->name = $this->name."的副本";
        }        function say(){
            echo "我的名字:" .$this->name.",性别:".$this->sex.",年龄:".$this->age."<br>";
        }
    }

String

toString()

The __toString() method is used to determine how a class should respond when it is treated as a string. It is the most convenient way to quickly obtain the string representation of an object. It is a method automatically called when directly outputting an object reference.

c8f1591198d8d8b7936b45c8259185d3foo = $foo;
} } public function __toString() {
      return $this->foo;
  }
}$class = new TestClass('Hello');echo $class;//Hello ?>

The object does not exist

call()

Call an inaccessible method in the object __call() will be called

callStatic()

When an inaccessible method is called in a static context, __callStatic() will be called

<?phpclass MethodTest {
    public function __call($name, $arguments) 
    {
        echo "Calling object method &#39;$name&#39; "
             . implode(&#39;, &#39;, $arguments). "
";
    }    public static function __callStatic($name, $arguments) 
    {
        echo "Calling static method &#39;$name&#39; "
             . implode(&#39;, &#39;, $arguments). "
";
    }
}

Auto-loading class

autoload()

In PHP5, you can define an __autoload() function, which will try Automatically called when using a class that has not yet been defined. By calling this function, the script engine has a last chance to load the required classes before PHP fails with an error

<?phpfunction __autoload($class_name) {
    require_once $class_name . &#39;.php&#39;;
}

Serialization

sleep()

  在调用serialize()函数将对象串行化时,检查类中是否存在一个魔术方法 __sleep()。如果存在,该方法会先被调用,然后才执行序列化操作。此功能可以用于清理对象,并返回一个包含对象中所有应被序列化的变量名称的数组。如果该方法未返回任何内容,则 NULL 被序列化,并产生一个 E_NOTICE 级别的错误

  __sleep()函数不需要接受任何参数,但需要返回一个数组,在数组中包含需要串行化的属性。未被包含在数组中的属性将在串行化时被忽略。如果没有在类中声明__sleep()方法,对象中的所有属性都将被串行化

wakeup()

  在调用unserialize()函数将对象反串行化对象时,则会自动调用对象中的__wakeup()方法,用来在二进制串重新组成一个对象时,为新对象中的成员属性重新初始化

  wakeup()经常用在反序列化操作中,例如重新建立数据库连接,或执行其它初始化操作

<?phpclass Connection {
    protected $link;    private $server, $username, $password, $db;  
    public function __construct($server, $username, $password, $db)
    {
        $this->server = $server;        $this->username = $username;        $this->password = $password;        $this->db = $db;        $this->connect();
    }    private function connect()
    {
        $this->link = mysql_connect($this->server, $this->username, $this->password);        mysql_select_db($this->db, $this->link);
    }    public function __sleep()
    {
        return array(&#39;server&#39;, &#39;username&#39;, &#39;password&#39;, &#39;db&#39;);
    }    public function __wakeup()
    {
        $this->connect();
    }
}?>

 

函数调用

invoke()

  当尝试以调用函数的方式调用一个对象时,__invoke()方法会被自动调用

<?phpclass CallableClass {
    function __invoke($x) {
        var_dump($x);
    }
}

【补充】

set_state()

  当调用var_export()导出类时,set_state()方法会被调用,本方法的唯一参数是一个数组,其中包含按 array('property' => value, ...) 格式排列的类属性

  [注意]var_export()返回关于传递给该函数的变量的结构信息,它和var_dump()类似,不同的是其返回的表示是合法的PHP代码,也就是说,var_export返回的代码,可以直接当作php代码赋给一个变量。 而这个变量就会取得和被var_export一样的类型的值

8c94170b7cb538fd32c57939f0221304var1 = $an_array['var1'];        $obj->var2 = $an_array['var2'];        return $obj;
   }
}

相关参考:php中文网

The above is the detailed content of Introduction to php magic methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51dev.com. If there is any infringement, please contact admin@php.cn delete