在字符串中包含常量而不连接
PHP 中有没有一种方法可以在字符串中包含常量而无需连接?
define('MY_CONSTANT', 42);
echo "This is my constant: MY_CONSTANT";
Is there a way in PHP to include a constant in a string without concatenating?
define('MY_CONSTANT', 42);
echo "This is my constant: MY_CONSTANT";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
有趣的是,您可以使用关键字“const”作为函数的名称,以防止名称空间乱放:
您还可以使用 $GLOBALS 在整个代码中传播“const”函数:
不确定将来使用是否安全。更糟糕的是——它看起来仍然很丑。
It is fun that you can use keyword 'const' as a name for your function to prevent namespace littering:
You can also use $GLOBALS to propagate 'const' function all over the code:
Unsure is it safe for future using. And what is worse - it's still looks ugly.
聚会迟到了,但如果你不喜欢 (s)printf ,这是我的解决方案:
Late to the party but here's my solution in case you don't like (s)printf :
这是一个老问题,但对于那些在这里搜索的人来说,这是另一种方法
This is an old question but for those searching here is another way to do it
我经常需要它,主要是在编写脚本时,打印新行字符。
从浏览器运行脚本时,换行符应该是
而从终端执行脚本时,它应该是PHP_EOL
所以,我做了类似的事情:
I need it pretty frequently, mostly while writing scripts, to print new line characters.
When running the script from browser, the newline should be
<br>
and while executing it from terminal it should bePHP_EOL
So, I do something like:
我相信这回答了OP最初的问题。唯一的事情是全局索引键似乎只能以小写形式工作。
输出:
I believe this answers the OP's original question. The only thing is the globals index key seems to only work as lower case.
Output:
不。
对于字符串,PHP 无法区分字符串数据和常量标识符。这适用于 PHP 中的任何字符串格式,包括 heredoc。
constant()
是获取常量的另一种方法,但函数调用也不能在没有连接的情况下放入字符串中。PHP 常量手册
No.
With Strings, there is no way for PHP to tell string data apart from constant identifiers. This goes for any of the string formats in PHP, including heredoc.
constant()
is an alternative way to get hold of a constant, but a function call can't be put into a string without concatenation either.Manual on constants in PHP
是的,它是(在某种程度上;)):
这可能不是您想要的,但我认为,从技术上讲,这不是连接,而是替换,并且从这个假设来看,它在字符串中包含一个常量而不连接。
Yes it is (in some way ;) ):
This is probably not what you were aiming for, but I think, technically this is not concatenation but a substitution and from this assumption, it includes a constant in a string without concatenating.
要在字符串中使用常量,您可以[1]使用以下方法:
如何
{$constant('ANIMAL')}
有效吗?字符串内的
{}
括号允许我们调用任何以$
开头的可调用函数!即
"I like {constant('ANIMAL')}";
没有$
将不会触发变量替换,因此我们必须将可调用对象放入一个变量。顺便说一下:
constant(...)
语法称为 第一类可调用语法。您还可以使用字符串函数名称 - 和任意参数
可以将任何函数名称放入变量中,并使用双引号字符串内的参数调用它。也适用于多个参数。
生产
还有匿名函数、数组等
产生:
生产:
在 3v4l.org 上亲自尝试 并注意 - 大多数可调用类型(除了
string< /code>)在 php5.3 之前不起作用(在最初撰写这篇文章的时间) - 现在更新到 php7++ 时代
请记住,
这种做法是不明智的,但可能性是存在的。
To use constants inside strings you can[1] use the following approach:
How does
{$constant('ANIMAL')}
work?The
{}
brackets inside string allow us to invoke any callable as long as it starts with$
!I.e.
"I like {constant('ANIMAL')}";
without$
will not trigger variable substitution so we have to put the callable in a variable.By the way: the
constant(...)
syntax is called first class callable syntax.You can also use string function names - and arbitrary parameters
One can place any function name in a variable and call it with parameters inside a double-quoted string. Works with multiple parameters too.
Produces
Also anonymous functions, arrays etc
Produces:
Produces:
Try it yourself on 3v4l.org and notice - most the callable types (except
string
) would not work pre-php5.3 (at the original time this post was written) - now updated to php7+++ eraKeep in mind
This practice is ill-advised, but the possibility is there.
如果您确实想要在不连接的情况下回显常量,这里是解决方案:
注意:在此示例中,echo 需要多个参数(查看逗号 ),所以它不是真正的串联
Echo 表现为一个函数,它需要更多的参数,它比串联更高效,因为它不需要串联然后回显,它只是回显所有内容,而不需要创建新的字符串连接对象:))
编辑
另外,如果您考虑连接字符串,将字符串作为参数传递或使用“编写整个字符串” > , , (逗号版本)总是最快的,接下来是 . (与 ' 单引号连接),最慢的字符串构建方法是使用双引号 ",因为以这种方式编写的表达式必须根据声明的变量和函数进行计算。
If you really want to echo constant without concatenation here is solution:
note: in this example echo takes a number of parameters (look at the commas), so it isn't real concatenation
Echo behaves as a function, it takes more parameters, it is more efficient than concatenation, because it doesn't have to concatenate and then echo, it just echoes everything without the need of creating new String concatenated object :))
EDIT
Also if you consider concatenating strings, passings strings as parameters or writing whole strings with " , The , (comma version) is always fastest, next goes . (concatenation with ' single quotes) and the slowest string building method is using double quotes ", because expressions written this way have to be evaluated against declared variables and functions..
你可以这样做:
You could do:
最简单的方法是
使用
(s)printf
的另一种方法The easiest way is
Another way using
(s)printf
正如其他人指出的那样,你不能这样做。 PHP 有一个函数
constant()
,它不能直接在字符串中调用,但我们可以轻松解决这个问题。及其用法的基本示例:
As others have pointed out you can not do that. PHP has a function
constant()
which cant be called directly in a string but we can easily work around this.and a basic example on its usage:
以下是其他答案的一些替代方案,这些答案似乎主要集中在“{$}”技巧上。尽管无法保证其速度;这都是纯粹的语法糖。对于这些示例,我们假设定义了下面的一组常量。
使用 extract()
这个很好,因为结果与变量相同。首先,您创建一个可重用的函数:
然后从任何范围调用它:
在这里,它将常量小写以便于您的手指操作,但您可以删除 array_change_key_case() 以保持它们原样。如果您已经有冲突的局部变量名称,则常量不会覆盖它们。
使用字符串替换
这与 sprintf() 类似,但使用单个替换标记并接受无限数量的参数。我确信有更好的方法可以做到这一点,但请原谅我的笨拙并尝试专注于其背后的想法。
像以前一样,您创建一个可重用函数:
然后从任何范围调用它:
您可以使用您想要的任何替换标记,例如 % 或 #。我在这里使用了斜杠,因为它更容易输入。
Here are some alternatives to the other answers, which seem to be focused mostly on the "{$}" trick. Though no guarantees are made on their speed; this is all pure syntactic sugar. For these examples, we'll assume the set of constants below were defined.
Using extract()
This one is nice because the result is identical to variables. First you create a reusable function:
Then call it from any scope:
Here, it lowercases the constants to be easier on your fingers, but you can remove the array_change_key_case() to keep them as-is. If you already have conflicting local variable names, the constants won't override them.
Using string replacement
This one is similar to sprintf(), but uses a single replacement token and accepts an unlimited number of arguments. I'm sure there are better ways to do this, but forgive my clunkiness and try to focus on the idea behind it.
Like before, you create a reusable function:
Then call it from any scope:
You can use any replacement token you want, like a % or #. I used the slash here since it's a bit easier to type.