Home > Backend Development > PHP Tutorial > Magic methods __call(), __clone(), __set(), __get() in php_PHP tutorial

Magic methods __call(), __clone(), __set(), __get() in php_PHP tutorial

WBOY
Release: 2016-07-12 09:04:23
Original
969 people have browsed it

Magic methods __call(),__clone(),__set(),__get()

__call($a,$v), when a method that does not exist or is not visible (modified with protected, private) in the class is called outside the class, __call(method name, array parameter) will be called automatically, and then it will be changed to The method passes 2 parameters, the first is the name of the called method, and the second is the passed parameter into the array. The __clone() method is triggered when an object of the class is cloned. __set($key,$val) triggers this method when setting an attribute that does not exist or is invisible (protected, private modified) in the class outside the class. At this time, 2 parameters are passed, the first is the attribute name, and the second is attribute value. __get($key) triggers this method when acquiring an attribute that does not exist or is invisible (protected, private modified) in the class outside the class. At this time, one parameter is passed, which is the attribute name. example:
<?php
class test{
    protected $a=1;
    private $b=2;
    public function __clone(){
        echo "有人要克隆我<br/>";
    }
    public function __call($name,$arg){
        echo "有人要调用不存在或不可见的方法名",$name,",第一个参数是$arg[0]<br/>";
    }
    public function __set($k,$v){
        echo "有人要设置不存在或不可见的属性",$k,"的值为",$v,"<br/>";
    }
    public function __get($k){
        echo "有人要获取不存在或不可见的属性",$k;
    }

}
Copy after login

$test1=new test();
$test3=$test1;//At this time $test3 and $test1 are the same object, that is, they both point to the same object
$test2=clone $test1;//After cloning, $test1 and $test2 are two different objects, although the stored values ​​​​are the same
$test1->abc(1,2,3);
$test1->a=3;
$test1->b;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1073355.htmlTechArticleMagic methods in php __call(), __clone(), __set(), __get() __call($ a, $v), when a method that does not exist or is not visible (modified with protected, private) in the class is called outside the class, it will be automatically called...
Related labels:
source:php.cn
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