类机制有关问题

WBOY
發布: 2016-06-13 13:24:35
原創
724 人瀏覽過

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

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

Test1类

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

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

登入後複製


Test2类
PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
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()
    }
 
}
<br><font color="#e78608">------解决方案--------------------</font><br>
我认为你的两个方案都不太好,而是合并起来比较好
登入後複製
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
    }
} <div class="clear">
                 
              
              
        
            </div>
登入後複製
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!