3

I have a constants I want to return by a function like this:

public function getConst($const)
{
    $const = constant("Client::{$const}");
    return $const;
}

But this is giving me an error:

constant(): Couldn't find constant Client::QUERY_SELECT

This however, does work:

public function getConst($const)
{
    return Client::QUERY_SELECT;
}

Why not?

jeremy
  • 9,965
  • 4
  • 39
  • 59
Dion Snoeijen
  • 94
  • 2
  • 11

2 Answers2

5

In fact this works just fine: http://3v4l.org/pkNXs

class Client {
    const QUERY_SELECT = 'foo';
}

$const = 'QUERY_SELECT';
echo constant("Client::{$const}");  // foo

The only reason this would fail is if you're in a namespace:

namespace Test;

class Client {
    const QUERY_SELECT = 'foo';
}

$const = 'QUERY_SELECT';
echo constant("Client::{$const}");  // cannot find Client::QUERY_SELECT

The reason for that is that string class names cannot be resolved against namespace resolution. You have to use the fully qualified class name:

echo constant("Test\Client::{$const}");

You may use the __NAMESPACE__ magic constant here for simplicity.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

If you want to use the ReflectionClass, it would work.

$reflection = new ReflectionClass('Client');
var_dump($reflection->hasConstant($const));

More verbose example, it might be over kill ( not tested )

public function getConst($const)
{
   $reflection = new ReflectionClass(get_class($this));
   if($reflection->hasConstant($const)) {
     return (new ReflectionObject($reflection->getName()))->getConstant($const);
   }
}
Ryan
  • 14,392
  • 8
  • 62
  • 102