在PHP中使用变量作为函数名称

在PHP中使用变量作为函数名称

本文介绍了在PHP中使用变量作为函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Is there a way of using a variable as a function name.

For example i have a variable

$varibaleA;

and I want to create a function i.e.

function $variableA() {
}

so this function can be called later in the script. Does anyone know if this can be done?

Thanks

解决方案

Declaring a function with a variable but arbitrary name like this is not possible without getting your hands dirty with eval() or include().

I think based on what you're trying to do, you'll want to store an anonymous function in that variable instead (use create_function() if you're not on PHP 5.3+):

$variableA = function() {
    // Do stuff
};

You can still call it as you would any variable function, like so:

$variableA();

这篇关于在PHP中使用变量作为函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:07