简体   繁体   English

如何将函数引用分配给变量?

[英]How to assign a function reference to a variable?

I would like to handle functions references and lambda in consistent way in PHP, but I have trouble when assigning a function reference to a variable. 我想在PHP中以一致的方式处理函数引用和lambda,但是将函数引用分配给变量时遇到麻烦。

function foo()
{
  echo "hi\n";
}

$here = function() { echo "hello\n"; };
$here = foo;

The last line gives me a warning. 最后一行给我警告。 I could use string literal, but I am afraid of two things -- using it later as string by mistake, and problems with name resolution when passing such string-reference over namespace boundaries. 我可以使用字符串文字,但是我担心两件事-稍后误将其用作字符串,以及在名称空间边界上传递此类字符串引用时名称解析出现问题。

Is there any way to grab that reference without using strings? 有没有不用字符串就可以获取该引用的方法?

One way is to create it as an anonymous function: 一种方法是将其创建为匿名函数:

$foo = function()
{
  echo "hi\n";
};

$foo();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM