zoukankan      html  css  js  c++  java
  • 魔术方法__get()、__set()和__call()的用法

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

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

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

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

    1. __call :  

    规则:

    mixed __call(string $namearray $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

    希望可以帮到大家!

  • 相关阅读:
    strcpy
    Apple Swift中英文开发资源集锦[apple swift resources]
    c/c++指针总结[pointer summary]
    TestPointer
    66. 有序数组构造二叉搜索树[array to binary search tree]
    HDU 2112 HDU Today
    HDU 3790 最短路径问题
    HDU 2544 最短路
    模拟赛 Problem 3 经营与开发(exploit.cpp/c/pas)
    模拟赛 Problem 2 不等数列(num.cpp/c/pas)
  • 原文地址:https://www.cnblogs.com/yuanwanli/p/5812109.html
Copyright © 2011-2022 走看看