php 類別裏如何呼叫自已的method來完成array_map()

參考:http://tw2.php.net/manual/en/language.pseudo-types.php#language.types.callback

To use object methods with array_map(), pass an array containing the object instance and the method name. For same-object scope, use $this as normal. Since your method name is defined in your public $func property, you can pass $this->func. This applies to most functions that accept a callback as an argument.

As a side note, the parentheses outside array_map() aren’t necessary.

return array_map(array($this, $this->func), range($min, $max));

重點的關鍵在使用 $this 變數,以下是我在類別中使用的寫法。這是在類別內相關聯的程式片段

    private $quarters_arr;
    private $item2index;
    private $index2item;
    function __construct(){
        parent::__construct();
        $quarters_arr=array();
        $item2index=array("electric_power"=>1,"derv"=>2,"natural_gas"=>38,"gas"=>3,"LPG"=>39,"tap_water"=>12);
        $index2item=array_flip($item2index);
    }

    function index2item($a){
        $a->item_id=$index2item[$a->item_id];
        return $a;
    }

    function get_quarter_energy_amount($target_quarter){
        $response_json_data=Array();
        $energy_use=$this->db->query("select * from carbon_energy_use_statistics where quarter='{$target_quarter}'");
        $energy_use_array=(array)$energy_use->result();
        $energy_use_array=array_map($this->index2item,$energy_use_array);
        $response_json_data['quarter']=$target_quarter;
        $response_json_data['production']=$this->db->query("select production from quarter_production where quarter='{$target_quarter}';")->row(1)->production;
        $response_json_data['usage_amount']=$energy_use_array;
        return (array)$response_json_data;
    }

codeigniter 類別中自訂義有函式使用「$this->index2item」

$energy_use_array=array_map($this->index2item,$energy_use_array);

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s