首页 > 其他 > 详细

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

时间:2019-04-15 23:09:44      阅读:159      评论:0      收藏:0      [点我收藏+]

刚开始学习魔术方法时对__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

 

希望可以帮到大家!

 

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

原文:https://www.cnblogs.com/sandea/p/10713443.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!