有关如何简化此代码的任何建议?

时间:2011-08-30 09:16:19

标签: php

示例1:

    $name                =$this->input->post('name', TRUE); 
    $address             =$this->input->post('address', TRUE);
    $website             =$this->input->post('website', TRUE);
    $phone               =$this->input->post('phone', TRUE);
    $fax                 =$this->input->post('fax', TRUE);  

它让我有很多代码,因为我允许用户输入许多信息......

3 个答案:

答案 0 :(得分:5)

使用循环:

$fields = array('name', 'address', 'website', 'phone', 'fax');

foreach($fields as $field) {
    ${$field} = $this->input->post($field, TRUE);
}

答案 1 :(得分:2)

您可以构建一个数组并完成它。

$fields = array(); // Use an array rather than single variables
$my_fields = array("name", "address", "website"); // etc. etc.

foreach ($my_fields as $field)
 $fields[$field] = $this->input->post($field, TRUE);

print_r($fields); // A nice array with all the field values

答案 2 :(得分:1)

更好的方法是将变量分组到数组中:

$keys = array ('name', 'address', 'website', 'phone', 'fax');
$data = array();
foreach($keys as $k){
    $data[$k] = $this->input->post($k, TRUE);
}

如果您愿意,您可以随时提取$ data,但我更喜欢将其保留在数组中

你应该把它放在一个函数中:

function fromRequest($method='post', $keys) {
    if ($method != 'post' && $method!= 'get') { throw new Exception('Invalid method'); }
    $data = array();
    foreach($keys as $k)
        $data[$k] = $this->input->$method($k, TRUE);
    return $data;
}