[英]Alternative of “use” in older PHP version
Anonymous function can be used as callback for function eg. 匿名函数可以用作函数的回调,例如。 array_map
and one of its advantage is usage of use
to use a variable from outside of the function. array_map
和它的一个优点是使用use
来从函数外部使用变量。 Eg.: 例如。:
$var = 10;
$x = array_map(function($e) use ($var) { if($var > 5) return $e['prop']; }, $myArray);
What about in older PHP version when callback has to be an existing function and function eg. 当回调必须是现有的函数和函数时,在较旧的PHP版本中呢? array_map
receives the function name as callback argument? array_map
接收函数名作为回调参数?
$var = 10;
$x = array_map("myFunction", $myArray);
function myFunction($e) {
//how to get $var here?
}
Please keep in mind that I'm looking for solution other than using global
variable. 请记住,我正在寻找除使用global
变量之外的解决方案。 Thanks. 谢谢。
Probably a dumb way to do it, but you could use an overloaded class with a static variable (so kind of like a global...). 可能是一种愚蠢的方式,但你可以使用带有静态变量的重载类(有点像全局......)。 I only suggest overloading because it works like a regular variable (in how you assign it). 我只建议重载,因为它就像一个常规变量(在你如何分配它)。
I'm sure someone who has worked with PHP longer than I have will have a better idea. 我确信使用PHP的人比我的工作时间更长。 Also I am not sure what "older version" means (how old "old" is) but the overloading goes back to at least 5.0/5.1. 此外,我不确定“旧版本”是什么意思(旧的“旧”),但重载至少回到5.0 / 5.1。 I think the closure is around 5.3 (according to this answer Which version of php add anonymous functions )? 我认为关闭是5.3左右(根据这个答案哪个版本的php添加匿名函数 )? This is not exactly the scenario, you have outlined, but the accessing of the value is made available without using a true global
: 这是不完全的情况下,你已经列出,但值的访问,而无需使用一个真正的提供global
:
class Overlord
{
private static $properties;
public static $val;
public function __get($property)
{
return (isset(self::$properties[$property]))? self::$properties[$property]:false;
}
public function __set($property,$value)
{
self::$val = self::$properties[$property] = $value;
}
public function __isset($property)
{
return (isset(self::$properties[$property]));
}
}
function myFunction($e) {
return Overlord::$val." overloaded PLUS -->".$e;
}
// Create the mighty overloader class
$ov = new Overlord();
// Assign a variable
$ov->val = 21;
// Random well-thought-out array
$myArray = array("One",1,"Two",2);
// Run through the first variable
$x = array_map("myFunction", $myArray);
// Assign a second random variable
$ov->stuff = 11;
// Run through the array again with new variable
$y = array_map("myFunction", $myArray);
// Array one
print_r($x);
// Array two
print_r($y);
Would give you something like: 会给你这样的东西:
Array
(
[0] => 21 overloaded PLUS -->One
[1] => 21 overloaded PLUS -->1
[2] => 21 overloaded PLUS -->Two
[3] => 21 overloaded PLUS -->2
)
Array
(
[0] => 11 overloaded PLUS -->One
[1] => 11 overloaded PLUS -->1
[2] => 11 overloaded PLUS -->Two
[3] => 11 overloaded PLUS -->2
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.