日期:2014-05-17  浏览次数:20434 次

类机制问题
上篇帖子没人气了,要问的问题没解决(估计没表达清楚)

先来2个类,这2个类主要是源数据的来源途径不同

Test1类
PHP code

class test1{
 
    protected $arr = array();
 
    function __construct($arr){
        $this->arr = $arr;
    }
 
    function t1(){
        //use $this->arr
    }
 
    function t2(){
        //use $this->arr
    }
 
}



Test2类
PHP code

class test2{
 
    function get_arr(){
        //get $arr from data
        return $arr;
    }
 
    function t1(){
        //use $this->get_arr())
    }
 
    function t2(){
        //use $this->get_arr()
    }
 
}



这2个类的区别就是得到源数据途径的区别
test1 是直接存在类属性中,初始化获取
test2 是通过get_arr函数从文件中获得

现在的问题是,
一:如果都调用一个类中函数(如 t1),test1类除了源数据$arr比test2进来得比较早(test1初始化时源数据$arr就有了,而test2是需要调用get_arr才能得到初始化数据$arr)外还有什么差别(只效率与内存上)?

二:这个主要的,就是如果一个页面都调用了t1和t2,test1类的arr数据应该只存在一份,test2的数据调用了2次get_arr,是否在内存中存在两个$arr数组???如果是这样的话是不是就放在类属性中比较好了?

上一个帖子的地址



------解决方案--------------------
两个问题你都可以简单测试

话说你了解下copy on write ,就知道,仅仅调用数组,不会引起数据内存中copy的

但当你类方法、函数中操作值改变的时候,而又无需保存原始数据,自然test1较好
类似test1方式,
function t(&$arr) ,就是为了避免大数据copy时候的写法。。。。php设计还是相当巧妙的
------解决方案--------------------
话说第二种一般也要cache住,不可能每次调用都直接读文件。
这样就没啥区别了。
PHP code
class test2{
    public static $data = array();
    function get_arr(){
        if(self::$data) return self::$data;
        //get $arr from data
        return $arr;
    }
 
    function t1(){
        //use $this->get_arr())
    }
 
    function t2(){
        //use $this->get_arr()
    }
 
}

------解决方案--------------------
我认为你的两个方案都不太好,而是合并起来比较好
PHP code
class test1{
    protected $arr = array();
    function __construct(){
        $this->arr = get_arr();
    }
    function get_arr(){
        //get $arr from data
        return $arr;
    }
    function t1(){
        //use $this->arr
    }
    function t2(){
        //use $this->arr
    }
}