首页 > 解决方案 > PHP - 将变量设置为等于函数,而不运行它

问题描述

您知道是否有一种方法可以在不执行函数的情况下在 php 中执行以下操作?

我希望 $test 等于函数,而不是它的结果。

$test = helloWorld();

function helloWorld() {
    echo "HelloWorld";
}

标签: phpfunctional-programming

解决方案


我认为最接近的方法是使用变量函数

function helloWorld() {
    echo "HelloWorld";
}

$test = 'helloWorld';
$test();

使用匿名函数也可以做到这一点。注意;函数声明之后。

$test = function () {
    echo "HelloWorld";
};

$test();

请参阅文档中的变量函数匿名函数


推荐阅读