如何判断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.

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.

You could do it like this:

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;
    }
}

However you would need to quote the string to call the function:

my_function("CONSTANT_NAME");

Also, this will only work if there is no variable whose value is the same as a defined constant name:

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

Try this:

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