为什么用 get

WBOY
Release: 2016-06-23 14:11:16
Original
1114 people have browsed it

    class xx{
       private $gg=30;
       function __get($cute){
           return $this->$cute;
       }
       function __set($n,$val){
           $this->$n=$val;
       }
    }
    $xxx=new xx();
    echo $xxx->gg;
?>

真要获取$gg。。。你把$gg设置为public不就完了?


回复讨论(解决方案)

是的,我也认为这是画蛇添足。但__get,__set()的实际用处远远不是这段简单的代码能表达的。
话说回来,魔术方法只是让调用变得更简单。

几乎所有的高级语言都提供了类属性的 Access 和 Assign 方法,用于在访问类属性的时候完成一些预设的动作,比如验证、计算
php 也不无例外的提供了 __get 和 __set 方法与之对应

对$gg的读取,写入控制  

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template