doucheng1063 2019-01-31 10:35 采纳率: 100%
浏览 94

连接命名空间类静态变量的最佳方法是什么?

In PHP we can do things like this:

$who = 'world';
$a = 'hello ' . $who;

or

$a = "hello $who";

or

$a = "hello {$who}"

Quoting Stephen Clay from php.net into the String operators section the last way is the best because when we use dots PHP is forced to re-concatenate all string. Also if we need to concat more variables, the last is a better way than the second way. But, Which is the best way if I have to concat a value from a class static variable ? PHP throws error if you try to concat the variable directly into a namespace class, without using dots. Only the first way shown before is allowed. I want to know if there is some another way to do this

ERROR:

$a = "hello 
amespace\classname::$who"; //NOTICE: undefined variable who
$b = "hello ${
amespace\classname::$who}"; //NOTICE: undefind variable classname
$c = "hello 
amespace\classname::${who}"; //NOTICE: undefine variable who.
$d = "hello {
amespace\classname::$who}"; //NOTICE: undefine variable who

I tried to explain with simple code, the really is that I need to concat a static variable from a class who I can't get an instance. If you get some class into a variable and later try to concat the static property this run correctly also

$who = new 
amespace\classname();
$a = "{$who::$who} $a"; // this run ok.
  • 写回答

2条回答 默认 最新

  • doucanshou6998 2019-01-31 11:23
    关注

    The problem with something like...

    $d = "hello {
    amespace\classname::$who}"
    

    is that the {} would normally expect just a variable to do a substitution, but as it sees amespace\classname is wouldn't know if this was a literal piece of text or not, so it defaults to being a literal and then gets to $who and so looks for a variable in the current namespace.

    If you can't get an instance of the class, you can still set a variable with the name of the class...

    $class = namespace\classname::class;
    echo "Hello {$class::$who}";
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度