類機制有關問題

來源:互聯網
上載者:User
類機制問題
上篇文章沒人氣了,要問的問題沒解決(估計沒表達清楚)

先來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    }} 
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.