且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP接受字符串,并检查该字符串是否作为变量存在

更新时间:2022-02-13 22:44:36

我会使用数组并自己检查数组键(或初始化我的所有变量...),但是对于您的函数,您可以使用类似以下内容的方法:>

I would use arrays and check for array keys myself (or initialize all my variables...), but for your function you could use something like:

function varIsset($var)
{   
    global $$var;
    return isset($$var) && !empty($$var);
}

查看有关变量变量的手册.您需要使用global $$var;来解决范围问题,所以这是一个令人讨厌的解决方案.在此处查看有效的示例.

Check out the manual on variable variables. You need to use global $$var; to get around the scope problem, so it's a bit of a nasty solution. See a working example here.

编辑:如果您需要返回的值,则可以执行以下操作:

If you need the value returned, you could do something like:

function valueVar($var)
{   
    global $$var;
    return (isset($$var) && !empty($$var)) ? $$var : NULL;
}

但是,老实说,在变量可能存在或不存在时使用类似的变量对我来说有点不对.

But to be honest, using variables like that when they might or might not exist seems a bit wrong to me.