【问题标题】:How to tell if a param was passed assuming it was a constant?假设参数是常量,如何判断参数是否通过?
【发布时间】:2013-08-14 14:11:07
【问题描述】:

我正在使用此代码(注意:HELLO_WORLD 从未定义!):

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

my_function(HELLO_WORLD);

HELLO_WORLD 可能已定义,也可能未定义。我想知道它是否被通过,如果HELLO_WORLD 被通过,假设它是恒定的。我不在乎HELLO_WORLD的值。

类似这样的:

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

如果参数是常量还是变量,我如何判断它是传递的?

我知道这不是很好的编程,但这是我想做的。

【问题讨论】:

标签: php constants


【解决方案1】:

试试这个:

$my_function ('HELLO_WORLD');

function my_function ($foo)
{
   $constant_list = get_defined_constants(true);
   if (array_key_exists ($foo, $constant_list['user']))
   {
      print "{$foo} is a constant.";
   }
   else
   {
      print "{$foo} is not a constant.";
   }
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    function my_function($Foo) {
        if (defined($Foo)) {
            // Was passed as a constant
            // Do this to get the value:
            $value = constant($Foo);
        }
        else {
            // Was passed as a variable
            $value = $Foo;
        }
    }
    

    但是你需要引用字符串来调用函数:

    my_function("CONSTANT_NAME");
    

    此外,这仅在没有值与定义的常量名称相同的变量时才有效:

    define("FRUIT", "watermelon");
    $object = "FRUIT";
    my_function($object); // will execute the passed as a constant part
    

    【讨论】:

    • 他想知道给定的参数是常量还是变量
    • 啊,我只是想他想知道它是否被定义。
    • @Mr.Alien 你是对的。我更新了我的问题以使用更好的措辞。
    【解决方案3】:

    如果未定义常量,PHP 会将其视为字符串(在本例中为“HELLO_WORLD”)(并在您的日志文件中添加通知)。

    可以进行如下检查:

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

    但遗憾的是,这段代码有两个大问题:

    • 您需要知道被传递的常量的名称
    • 常量不能包含它自己的名字

    更好的解决方案是传递常量名而不是常量本身:

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

    为此,您唯一需要更改的是传递一个常量的名称,而不是常量本身。好消息:这也将防止在您的原始代码中引发通知。

    【讨论】:

    • 你的第一句话是最有帮助的。我注意到之前未定义的常量被转换为字符串,但在提问时没有考虑到它。我想我可能只需要考虑另一种方式来做我想做的事。
    猜你喜欢
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    相关资源
    最近更新 更多