0

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.

Jared
  • 2,978
  • 4
  • 26
  • 45

3 Answers3

1

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.

oezi
  • 51,017
  • 10
  • 98
  • 115
  • Your first sentence is the most helpful. I've noticed that undefined constants were converted to strings before, but didn't consider it when asking the question. I think I might just have to think of an alternative way of doing what I want. – Jared Aug 13 '13 at 05:11
0

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
Mike
  • 23,542
  • 14
  • 76
  • 87
0

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.";
   }
}
Sutandiono
  • 1,748
  • 1
  • 12
  • 21