【问题标题】:PHP Class constant with php function constant giving warningPHP 类常量与 php 函数常量给出警告
【发布时间】:2014-09-03 16:56:37
【问题描述】:

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

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;
}

为什么不呢?

【问题讨论】:

  • 你可以试试反射类。
  • 啊哈!那太棒了。这样可行!如果您给出答案,我可以将其标记为已回答。
  • 不,这个问题可能是重复的。很高兴它起作用了。

标签: php constants class-constants


【解决方案1】:

事实上这很好用: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__ 魔术常数。

【讨论】:

  • 是的,你是对的。我在一个命名空间中。那一定是问题所在。现在我使用反射,它也在工作。
  • 但这当然也有效:return constant('Solarium\Core\Client\Client::' . $const);
  • 不幸的是,__NAMESPACE__ 没有帮助,如果我在另一个命名空间中,而不是具有我想用别名引用的常量的类(使用 use)。
  • @Jānis 是的,那么你需要使用完全限定的类名。
【解决方案2】:

如果你想使用 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);
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2020-12-20
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多