php闭包(匿名函数)


环境php7.0

今天在用phalcon框架时,导入配置文件后,依赖注入一直出问题:

<?php
require '../config/config.php';
$config = new \Phalcon\Config($setting);

$di['db'] = function () {
    $connection = new \MongoDB\Driver\Manager($config->mongodb->url);
    return $connection;
};

错误日志提示,变量$config未定义。这个问题就是php闭包的概念导致的。

闭包的书写格式

其关键字只有use,将外界变量与闭包联系起来:

$a = function($arg) use($b,$c){
	echo $b;
}

闭包的常见用途

传递参数

<?php
$a = "hello";
$test = function ($arg) use ($a) {
	echo($a.$arg);
};
$test("world");

打印结果

helloworld

猜你喜欢

转载自blog.csdn.net/qq_39985298/article/details/89167436