如何判断一个参数是否是在假定它是常量的情况下传递的


How to tell if a param was passed assuming it was a constant?

我正在使用此代码(注意: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会将其视为字符串(在本例中为"HELLO_WORLD")(并向日志文件中抛出通知)。

可以进行如下检查:

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

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

  • 您需要知道传递的常量的名称
  • 康斯坦德可能没有自己的名字

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

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

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

你可以这样做:

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

试试这个:

$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.";
   }
}