魔术方法__get()、__set()和__call()的用法

刚开始学习魔术方法时对__get()、__set() 和__call()的用法和作用不是太了解,也有一些误解。。。

现在分享一下个人的理解,大家共勉一下:

__get()、__set() 和__call()是很常用的,虽然不像__construct、__destruct运用的那么多,但是它们地位也是毋庸置疑的,

__construct、__destruct大家肯定非常熟悉了,在这就不多说了,直接看—————__get()、__set() 和__call();

1. __call :  

规则:

mixed __call(string $name,array $arguments)

当调用类中不存在的方法时,就会调用__call();

为了更好的理解,看一下例子:

<?php
class Test{
     public function __call($method,$args){
          echo $method;
          var_dump($args);
        }   
    }  
     $ob=new Test();
     $ob->hello(1,2);
?>

上面的例子将输出:

hello

Array(

[0]=>1

[1]=>2

2.__get() 和__set():

规则:

get :
mixed __get(string $name)
set:
void __set(string $name ,mixed $value)

__get()是访问不存在的成员变量时调用的;

__set()是设置不存在的成员变量时调用的;

为了更好的理解,看一下例子:

<?php
class Test{
       public $c=0;
       public $arr=array();
       
       public function __set($x,$y){
            echo $x . "/n";
            echo $y . "/n";
            $this->arr[$x]=$y;
        }    
        public function __get($x){
            echo "The value of $x is".$this->arr[$x];

        }   
} 
$a = new Test;
$a->b = 1 ;//成员变量b不存在,所以会调用__set
$a->c  = 2;//成员变量c存在,所以无任何输出
$d=$a->b;//  成员变量b不存在,所以会调用__get     
?>

上面的例子将输出:

b

1

The value of b is 1

希望可以帮到大家!

猜你喜欢

转载自www.cnblogs.com/sandea/p/10713443.html