`

常用的几个魔术变量

 
阅读更多

 

一、魔术方法__get 和 __set的使用:管理类中不存在的变量属性成员

 

在类中使用该两个函数

class Test{

 

    protected $arr = array();

    protected $page = 10;

 

    public function __set( $key, $value ){

        echo __METHOD__;

        $this->arr[$key] = $value;

    }

 

    public function __get( $key ){

        echo __METHOD__;

        return $this->arr[$key];

    }

}

 

使用示例

$test = new Test();

$test->title = "hello";  //给不存在的类的变量属性赋值时候会调用__set函数

echo $test->title;       //使用不存在的变量时候会调用_get函数

 

 

//__call管理类中不存在的非静态方法,__callStatic则管理不存在的静态方法

 

class Test{

 

    public function __call( $func, $param ){

        var_dump(__METHOD__);

        var_dump($func);

        var_dump($param);

 

        $err = $func."方法不存在";

        echo $err;

    }

   

     static public function __callStatic( $func, $param ){

 

        $err = $func."静态方法不存在";

        echo $err;

    }

 

}

 

$test = new Test();

$test->demo();      //当使用类中不存在的方法时候,会使用到定义的__call方法

 

 

 

//__toString方法是当直接输出一个对象时候,可以通过调用该方法输出字符串形式的类的名称

 

Class Test{

   

    public function __toString(){

        return __CLASS__;

    } 

}

 

$test = new Test();

 echo $test;  //调用__toString方法

 

 

 

 //__invoke方法:把对象当做方法使用时候会调用

 

Class Test(){

     public function __invoke( $param = ''){

        var_dump($param);

        return "ggggg";

    }

}

 

$test = new Test();

echo $test('fff');

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics