PHP Class constant with php function constant giving warning
class-constants, constants, php
Solution
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.
Problem
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?