php重载的一个用法

     在php中,实现了变量的get和set方法的重载,在5.1.0之后又实现了两个方法的重载,分别为__isset()和__unset()。注意这些方法不能被声明为static方法。

     而在方法的重载上提供了__call(string name, array arguments )函数,该函数将会返回被执行方法的返回值,其调用是在函数在该类中未被找到之后。

     可能这么讲比较抽象,更直观的方式是,我们找一个实际中的应用。在java之中,会经常使用到setter和getter方式。比如,setData() 就是设置一个data变量的值来实现。那么在php中我们可以这么做。我们可能需要设置一个类似存储器的东西,来管理我们放置类中的所有变量。那么我们可以这么实现。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 public function __call($method, $args)
    {
        switch (substr($method, 0, 3)) {
            case 'get' :
 
                $key = $this->_underscore(substr($method,3));
                $data = $this->getData($key, isset($args[0]) ? $args[0] : null);

            case 'set' :


                $key = $this->_underscore(substr($method,3));
                $result = $this->setData($key, isset($args[0]) ? $args[0] : null);
                return $result;

        }
    }

       事实上在那么可以很轻易的把一些关键数据放置于data之中。甚至在你需要的缓存它们。

Share
Posted in php at February 5th, 2010. No Comments.