為什麼 php 類別中成員變數前面需要冠上 var 字串 What does PHP keyword ‘var’ do?

From: http://stackoverflow.com/questions/1206105/what-does-php-keyword-var-do

這是用在 php4 的類別成員變數的宣告,也適用於 php5 。但因為 php5 配置較為嚴僅(E_STRICT)的關係 冠上 var 會被提出警告。

It’s for declaring class member variables in PHP4, and is no longer needed. It will work in PHP5, but will raise an E_STRICT warning in PHP from version 5.0.0 up to version 5.1.2, as of which it has been deprecated.

Example usage:

class foo {
    var $x = ‘y’; // or you can use public like…
    public $x = ‘y’; //this is also a class member variables.
    function bar() {}
}

var keyword 是在 PHP4 中宣告類別成員變數用的,而在 PHP5 中則改用 public、protext、private, 當然還是可以使用var宣告成員變數,但是不建議這樣做。

The var keyword is used to declare variables in a class in PHP 4:

class Foo {
    var $bar;
}

With PHP 5 property and method visibility (public, protected and private) was introduced and thus var is deprecated.

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);