声明多个变量的方法

时间:2013-12-02 17:26:45

标签: php

我有以下代码块:

$ship = $this->get_address($this->dealer_num);
$bill = $this->get_address($this->bill_to_num);

$this->ship_name =     $ship['CMNAME'];
$this->ship_address1 = $ship['CMLNE1'];
$this->ship_address2 = $ship['CMLNE2']!='' ? $ship['CMLNE2'] : NULL;
$this->ship_address3 = $ship['CMLNE2']!='' ? $ship['CMLNE3'] : NULL;
$this->ship_city =     $ship['CMCITY'];
$this->ship_state =    $ship['CMST'];
$this->ship_zip =      $ship['CMZIP'];
$this->ship_country =  $ship['CMCTRY'];

$this->bill_name =     $bill['CMNAME'];
$this->bill_address1 = $bill['CMLNE1'];
$this->bill_address2 = $bill['CMLNE2']!='' ? $bill['CMLNE2'] : NULL;
$this->bill_address3 = $bill['CMLNE3']!='' ? $bill['CMLNE3'] : NULL;
$this->bill_city =     $bill['CMCITY'];
$this->bill_state =    $bill['CMST'];
$this->bill_zip =      $bill['CMZIP'];
$this->bill_country =  $bill['CMCTRY'];

以下是get_address的定义:

private function get_address($key) {
      $result = db_query('SELECT CMNAME, CMLNE1, CMLNE2,
                          CMLNE3, CMCITY, CMST, CMZIP, CMCTRY
                          FROM myTable
                          WHERE C1STKY = :key;',
                         array(':key' => $key));  
      $info = $result->fetch(PDO::FETCH_ASSOC);
      return $info;
}

宣布这些变量的替代方法是什么?我讨厌只是变量声明的大长列表。是否有更优雅的方式来声明这些?

1 个答案:

答案 0 :(得分:0)

我最终解决这个问题的方法是改变我的类定义。我没有为每个地址组件提供类属性,而只是改变了我的类定义,将地址存储为关联数组。这种方式感觉更干净。

因此,上面的代码变成了

$this->shipping_address = $this->get_address($this->dealer_num);
$this->billing_address = $this->get_address($this->bill_to_num);