PHP use() 函数的作用域? [英] PHP use() function for scope?

查看:22
本文介绍了PHP use() 函数的作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过这样的代码:

function($cfg) use ($connections) {}

但 php.net 似乎没有提到该功能.我猜这与范围有关,但如何?

but php.net doesn't seem to mention that function. I'm guessing it's related to scope, but how?

推荐答案

use 不是函数,它是 闭包语法.它只是让外部作用域的指定变量在闭包内部可用.

use is not a function, it's part of the Closure syntax. It simply makes the specified variables of the outer scope available inside the closure.

$foo = 42;

$bar = function () {
    // can't access $foo in here
    echo $foo; // undefined variable
};

$baz = function () use ($foo) {
    // $foo is made available in here by use()
    echo $foo; // 42
}

例如:

$array = array('foo', 'bar', 'baz');
$prefix = uniqid();

$array = array_map(function ($elem) use ($prefix) {
    return $prefix . $elem;
}, $array);

// $array = array('4b3403665fea6foo', '4b3403665fea6bar', '4b3403665fea6baz');

这篇关于PHP use() 函数的作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆