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

    希望可以帮到大家!

  • 相关阅读:
    原生searchView 自定义样式
    面试问题总结
    Android Studio开发环境搭建
    JAVA基本程序设计结构
    JAVA大数使用
    sql
    普通树的递归遍历
    6_43_递归交换二叉树中所有节点的左右子树
    6_42_二叉树递归求叶子节点个数
    6_44_二叉树中值为x的节点为根的子树的深度
  • 原文地址:https://www.cnblogs.com/yuanwanli/p/5812109.html
Copyright © 2011-2022 走看看