drl2051 2014-07-13 17:21
浏览 61
已采纳

PHP类常量与php函数常量给出警告

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?

  • 写回答

2条回答 默认 最新

  • duandi1636 2014-07-13 17:57
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集