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?

4
  • 1
    You could try a reflection class. Commented Jul 13, 2014 at 17:23
  • Aha! That's great. That works! If you give an answer I can mark it as answered. Commented Jul 13, 2014 at 17:37
  • Nah this question is probably a duplicate anyways. Glad it worked though. Commented Jul 13, 2014 at 17:44
  • possible duplicate of Can I get CONST's defined on a PHP class? Commented Jul 13, 2014 at 17:44

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, you are correct. I'm in a namespace. That must have been the problem. Right now I use reflection and it's working too.
But surely this is working too: return constant('Solarium\Core\Client\Client::' . $const);
Unfortunately, __NAMESPACE__ doesn't help if I'm in another namespace than the class with the constant which I want to refer to with an alias (using use).
@Jānis Yeah, then you need to use the fully qualified class name.
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);
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.