内蒙之家 2016-10-21 09:24:24 6492次浏览 2条评论 8 1 0

php闭包语法介绍:

function callback($callback) {
    $callback();
}
callback(function() {
    print "This is a anonymous function.<br />/n";
});

//输出: This is a anonymous function.
/n

php5.3 新增闭包 use() 用法:

$msg = "Hello, everyone";
$callback = function () use ($msg) {
    print "This is a closure use string value, msg is: $msg. <br />/n";
};
callback($callback);

//输出: This is a closure use string value, msg is: Hello, everyone.
/n

项目中闭包常见处在使用 Yii的gridView生成页面时,字段值的输出会用到闭包函数, 代码如下:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        $pk_id,
        'summary',
        [
            'attribute'=> img,
            'format'  => 'html',
            'value'    => function($model) {
                return Html::img(FileHelper::ShowImg($model->img,array('size'=>'small')));
            }
        ],
    ],
]) ?>

此处的闭包函数, 框架支持传入一个变量,一般传入 $model, 也就是结果集遍历中的当前元素,我们可以在闭包函数中访问到当前元素的所有属性, 可是如果我们想访问的数据不在 $model 结果集中, 只是前面代码中出现过的某个变量, 这个时候我们可以使用 use() 关键字, 比如下面代码,我们在Controller中定义一个变量 $img_field,在GridView的闭包中使用这个变量。

<?php
    $img_field = 'xxx';
?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        $pk_id,
        'summary',
        [
            'attribute'=> $img_field,
            'format'  => 'html',
            'value'    => function($model) use ($img_field){
                return Html::img(FileHelper::ShowImg($model->$img_field,array('size'=>'small')));
            }
        ],
    ],
]) ?>
觉得很赞
  • 评论于 2016-10-22 15:41 举报

    好,请教一下,DetailView 部件中的值属性怎么才能使用函数呢

    [    
     'label' => '新建时间',
     'value' => $model->created_at,
    ],
    

    这样可以,但是使用函数就报错。请问有什么解决办法吗

    3 条回复
    评论于 2016-10-22 21:37 回复
                     <?= DetailView::widget([
    		        'model' => $model,
    		        'attributes' => [
    		            'name',
    		            'create_at:datetime'
    		        ],
    		    ]) ?>
    你是要格式化时间么?这样可以
    
    评论于 2016-10-22 21:49 回复

    想自己定义时间格式就这样:

                <?= DetailView::widget([
    		        'model' => $model,
    		        'attributes' => [
    		            'name',
    		            [
    		                'attribute' => 'create_datetime',
    		                'format'    => ['Datetime', 'Y-m-d H:i:s'],
    		                'value'     => $model->create_datetime,
    		            ],
    		        ],
    		    ]) ?>
    
    评论于 2017-01-05 15:56 回复
  • 评论于 2016-12-03 11:03 举报

    function(){
    }
    这个里面有时有多个参数,是为啥呢

您需要登录后才可以评论。登录 | 立即注册