3

我有一个常量,我想通过这样的函数返回:

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

但这给了我一个错误:

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

然而,这确实有效:

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

为什么不?

4

2 回答 2

4

事实上,这很好用:http: //3v4l.org/pkNXs

class Client {
    const QUERY_SELECT = 'foo';
}

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

这将失败的唯一原因是如果您在命名空间中:

namespace Test;

class Client {
    const QUERY_SELECT = 'foo';
}

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

原因是字符串类名无法根据命名空间解析来解析。您必须使用完全限定的类名:

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

为简单起见,您可以在__NAMESPACE__此处使用魔术常数。

于 2014-07-13T17:57:01.097 回答
1

如果你想使用 ReflectionClass,它会起作用。

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

更详细的例子,它可能是过度杀戮(未测试)

public function getConst($const)
{
   $reflection = new ReflectionClass(get_class($this));
   if($reflection->hasConstant($const)) {
     return (new ReflectionObject($reflection->getName()))->getConstant($const);
   }
}
于 2014-07-13T18:07:29.687 回答