简体   繁体   English

PHP 中字符串中的 Class 常量

[英]Class constant in a string in PHP

My reading of the manual (the bit just before the section heading "String access and modification by character") is that you can do some fancy tricks with class constants and {} inside a string but you can't do the simple thing that would make this method return the truth:对手册的阅读(在标题“字符串访问和按字符修改”之前的部分)是您可以使用 class 常量和 {} 在字符串中做一些花哨的技巧,但您不能做简单的事情让这个方法返回真相:

class c {
    const k = '12';
    public function s() {
        return "Twelve in decimal is {c::k}.";
    }
}

Is the right solution here to concatenate?这里是连接的正确解决方案吗?

Is the right solution here to concatenate?这里是连接的正确解决方案吗?

Yes.是的。 The extended curly syntax doesn't support it.扩展的 curly 语法不支持它。

Alternatively, you could export the list of constants to an array and use it (or export the constant to a single scalar variable name), but that's not really a good solution IMO.或者,您可以将常量列表导出到数组并使用它(或将常量导出到单个标量变量名称),但这并不是一个很好的解决方案 IMO。

Note that constants are available, as you can do this:请注意,常量是可用的,您可以这样做:

const k = 'foo';
$foo = 'bar';
echo "{${c::k}}"

giving you bar , but that's not what you want.给你bar ,但这不是你想要的。

It's a little cryptic, but there is a note on this in the manual.这有点神秘,但手册中有关于此的说明。

Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.使用单个花括号 ({}) 将无法访问函数或方法的返回值或 class 常量或 static class 变量的值。

The last sentence tells you it won't work so yes, concatenation is the way to go here .最后一句话告诉你它不会起作用,所以是的,连接是 go 这里的方式


(modified) Example of above paragraph: (修改)以上段落的例子:

<?php
class beers {
    const softdrink = 'rootbeer';
}

$rootbeer = 'A & W';

// This works; outputs: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";

// This won't work; outputs: I'd like an {beers::softdrink}
echo "I'd like an {beers::softdrink}\n";

The curly syntax only works for 'variable expressions'. curly 语法仅适用于“变量表达式”。 And you need anything that you can access with {$ .你需要任何可以使用{$访问的东西。

Oh, there's only that workaround:哦,只有那个解决方法:

    $c = "constant";
    return "Twelve in decimal is {$c('c::k')}.";

Which is obviously not much shorter or more readable than just using string concatenation here.这显然比在这里使用字符串连接更短或更易读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM