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

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 に答える