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 $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

    希望可以帮到大家!

  • 相关阅读:
    哪种可以让程序员赚到更多钱?
    layer 弹框 很好用 页面交互不好弄!!!父子弹框的交互!
    博客导航
    扯淡扯着扯着就远了----关键字;宁静致远
    高驰涛——裸奔到北京的程序猿
    TP5分页类使用——超级简单好用
    七牛云同步资源工具使用说明
    短链接实现原理和简单调用
    抓包工具Charles下载地址及Charles配置https
    敲代码的少年
  • 原文地址:https://www.cnblogs.com/sandea/p/10713443.html
Copyright © 2011-2022 走看看