dua27031 2013-08-13 04:57
浏览 21
已采纳

如何判断param是否通过假设它是一个常数?

I am using this code (note: HELLO_WORLD was NEVER defined!):

function my_function($Foo) {
    //...
}

my_function(HELLO_WORLD);

HELLO_WORLD might be defined, it might not. I want to know if it was passed and if HELLO_WORLD was passed assuming it was as constant. I don't care about the value of HELLO_WORLD.

Something like this:

function my_function($Foo) {
    if (was_passed_as_constant($Foo)) {
        //Do something...
    }
}

How can I tell if a parameter was passed assuming it was a constant or just variable?

I know it's not great programming, but it's what I'd like to do.

  • 写回答

3条回答 默认 最新

  • dongyong6428 2013-08-13 05:07
    关注

    if a constant isn't defined, PHP will treat it as String ("HELLO_WORLD" in this case) (and throw a Notice into your Log-files).

    You could do a check as follows:

    function my_function($foo) {
        if ($foo != 'HELLO_WORLD') {
            //Do something...
        }
    }
    

    but sadly, this code has two big problems:

    • you need to know the name of the constant that gets passed
    • the constand musn't contain it's own name

    A better solution would be to pass the constant-name instead of the constant itself:

    function my_function($const) {
        if (defined($const)) {
            $foo = constant($const);
            //Do something...
        }
    }
    

    for this, the only thing you have to change is to pass the name of a constant instead of the constant itself. the good thing: this will also prevent the notice thrown in your original code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?