1. 程式人生 > >魔術方法__get()、__set()和__call()的用法

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

魔術方法 調用 不存在 public clas set 開始 rgs con

剛開始學習魔術方法時對__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()的用法