PHP中extract 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
//)
?>
 

 

 
 
 
 
 
 
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值