PHP中extract() array_map call_user_func compact

近日在看一个牛人的代码时,看到一个非常好用的函数:extract(),它的主要作用是将数组展开,键名作为变量名,元素值为变量值,可以说为数组的操作 提供了另外一个方便的工具,比方说,可以很方便的提取$_POST或者$_GET的元素,对表单提交上来的内容不能不用一一赋值,直接使用下面代码:

edit.html

<form method="post" name="myform" id="myform">
    <table cellpadding="2" cellspacing="1" class="table_form" width="100%">
        <tr>
            <th width="100"><?php echo L('serviceurl') ?>:</th>
            <td><input type="text" name="openservice[serviceurl]" value="<?php echo $serviceurl; ?>"></td>
        </tr>

        <tr>
            <th width="100"><?php echo L('servicename') ?>:</th>
            <td><input type="text" name="openservice[servicename]" value="<?php echo $servicename; ?>"></td>
        </tr>
        <input type="submit" name="dosubmit" id="dosubmit" value=" <?php echo L('submit') ?> ">
    </table>
</form> 

在action.php中只要使用extract()函数将$_POST['openservice']全局数据解开:

action.php

<?php
//保存时,需要的内容用$_POST['openservice'],不需要保存的用$_POST['info']
$_POST['openservice'] = array_map('trim', $_POST['openservice']);
$this->db->insert($_POST['openservice']);

//回显修改
extract($_POST['openservice']);
//相当于$username = $_POST['openservice']['username'];
//$password = $_POST['openservice']['password'];
?>

 数据库查询代理

<?php
class Brand 
{
    public function insert($data){
    }

    public static function update($data, $where = ""){
    }

    public function delete($id){
    }

//重写机器人:Brand::robot(array('method'=>'save','params'=>array('data'=>'someData')) );
    public static function robot(array $settings)
    {
        $data = array();
        $obj = new self();
        extract($settings['params']);
        switch ($settings['method']) {
            case 'save':
                $data = $obj->insert($data);
                break;

            case 'update':
                $data = $obj->update($data, $where);
                break;
            default:
                break;
        }
        return $data;
    }

 以上代码用系统自带方法也可以实现

//use for static method
call_user_func_array(array("Brand", "update"), array($data, $where)); 
call_user_func(array("Brand", "update"), $data, $where);
// or  
$obj = new Brand;
call_user_func(array($obj, "update"), $data, $where)

compact是extract的反向的

<?php
$firstname = "Peter";
$lastname = "Griffin";
$age = "38";

$result = compact("firstname", "lastname", "age");
print_r($result);
//Array
//(
//[firstname] => Peter
//[lastname] => Griffin
//[age] => 38
//)
?>
 

 

 
 
 
 
 
 
 
 

你可能感兴趣的:(PHP)