php 在字符串中包含常量而不连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2203943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Include constant in string without concatenating
提问by Brian
Is there a way in PHP to include a constant in a string without concatenating?
PHP 中有没有办法在不连接的情况下在字符串中包含常量?
define('MY_CONSTANT', 42);
echo "This is my constant: MY_CONSTANT";
采纳答案by Pekka
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.
使用字符串,PHP 无法将字符串数据与常量标识符区分开来。这适用于 PHP 中的任何字符串格式,包括 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.
constant()是获取常量的另一种方法,但函数调用也不能在没有连接的情况下放入字符串中。
回答by Felix Kling
Yes it is (in some way ;) ):
是的(以某种方式;)):
define('FOO', 'bar');
$test_string = sprintf('This is a %s test string', FOO);
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.
这可能不是您的目标,但我认为,从技术上讲,这不是连接而是替换,并且从这个假设来看,它在字符串中包含一个常量而不连接。
回答by raveren
To use constants inside strings you can use the following method:
要在字符串中使用常量,您可以使用以下方法:
define( 'ANIMAL', 'turtles' );
$constant = 'constant';
echo "I like {$constant('ANIMAL')}";
How does this work?
这是如何运作的?
You can use any string function name 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.
可以将任何函数名称放在变量中,并使用双引号字符串中的参数调用它。也适用于多个参数。
$fn = 'substr';
echo "I like {$fn('turtles!', 0, -1)}";
Produces
生产
I like turtles
我喜欢乌龟
Anonymous functions too
匿名函数
You can also use anonymous functions provided you're running PHP 5.3+.
如果您运行的是 PHP 5.3+,您也可以使用匿名函数。
$escape = function ( $string ) {
return htmlspecialchars( (string) $string, ENT_QUOTES, 'utf-8' );
};
$userText = "<script>alert('xss')</script>";
echo( "You entered {$escape( $userText )}" );
Produces properly escaped html as expected.
按预期生成正确转义的 html。
Callback arrays not allowed!
不允许回调数组!
If by now you are under the impression that the function name can be any callable, that's not the case, as an array that returns true when passed to is_callablewould cause a fatal error when used inside a string:
如果现在您认为函数名称可以是任何可调用的,那么事实并非如此,因为在传递给时返回 true 的数组is_callable在字符串中使用时会导致致命错误:
class Arr
{
public static function get( $array, $key, $default = null )
{
return is_array( $array ) && array_key_exists( $key, $array )
? $array[$key]
: $default;
}
}
$fn = array( 'Arr', 'get' );
var_dump( is_callable( $fn ) ); // outputs TRUE
// following line throws Fatal error "Function name must be a string"
echo( "asd {$fn( array( 1 ), 0 )}" );
Keep in mind
记住
This practice is ill-advised, but sometimes results in much more readable code, so it's up to you - the possibility is there.
这种做法是不明智的,但有时会导致代码可读性更高,所以这取决于您 - 可能性是存在的。
回答by Macswork
define( 'FOO', 'bar');
$FOO = FOO;
$string = "I am too lazy to concatenate $FOO in my string";
回答by thetaiko
define('FOO', 'bar');
$constants = create_function('$a', 'return $a;');
echo "Hello, my name is {$constants(FOO)}";
回答by Juraj Blahunka
If you really want to echo constant without concatenationhere is solution:
如果你真的想在没有连接的情况下回显常量,这里是解决方案:
define('MY_CONST', 300);
echo 'here: ', MY_CONST, ' is a number';
note: in this example echo takes a number of parameters (look at the commas), so it isn't real concatenation
注意:在这个例子中,echo 接受了一些参数(看看逗号),所以它不是真正的串联
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 :))
Echo 表现为一个函数,它需要更多的参数,它比串联更有效,因为它不必串联然后回显,它只是回显所有内容而无需创建新的 String 串联对象:))
EDIT
编辑
Also if you consider concatenatingstrings, passings strings as parametersor 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..
此外,如果您考虑连接字符串,将字符串作为参数传递或使用 "编写整个字符串,,(逗号版本)总是最快的,接下来是.(用'单引号连接),最慢的字符串构建方法是使用双引号",因为以这种方式编写的表达式必须针对声明的变量和函数进行评估。
回答by Simon
You could do:
你可以这样做:
define( 'FOO', 'bar' );
$constants = get_defined_constants(true); // the true argument categorizes the constants
$constants = $constants[ 'user' ]; // this gets only user-defined constants
echo "Hello, my name is {$constants['FOO']}";
回答by Yamiko
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.
正如其他人指出的那样,你不能这样做。PHP 有一个constant()不能在字符串中直接调用的函数,但我们可以很容易地解决这个问题。
$constant = function($cons){
return constant($cons);
};
and a basic example on its usage:
及其用法的基本示例:
define('FOO', 'Hello World!');
echo "The string says {$constant('FOO')}";
回答by Jekis
The easiest way is
最简单的方法是
define('MY_CONSTANT', 42);
$my_constant = MY_CONSTANT;
echo "This is my constant: $my_constant";
Another way using (s)printf
另一种使用方式 (s)printf
define('MY_CONSTANT', 42);
// Note that %d is for numeric values. Use %s when constant is a string
printf('This is my constant: %d', MY_CONSTANT);
// Or if you want to use the string.
$my_string = sprintf('This is my constant: %d', MY_CONSTANT);
echo $my_string;
回答by Beejor
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.
以下是其他答案的一些替代方案,这些答案似乎主要集中在“{$}”技巧上。虽然不能保证它们的速度;这都是纯粹的语法糖。对于这些示例,我们假设定义了以下常量集。
define( 'BREAD', 'bread' ); define( 'EGGS', 'eggs' ); define( 'MILK', 'milk' );
Using extract()
This one is nice because the result is identical to variables. First you create a reusable function:
使用extract()
这个很好,因为结果与变量相同。首先创建一个可重用的函数:
function constants(){ return array_change_key_case( get_defined_constants( true )[ 'user' ] ); }
Then call it from any scope:
然后从任何范围调用它:
extract( constants() );
$s = "I need to buy $bread, $eggs, and $milk from the store.";
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.
在这里,它将常量小写以方便您的手指使用,但您可以删除 array_change_key_case() 以保持它们原样。如果您已经有冲突的局部变量名称,则常量不会覆盖它们。
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.
使用字符串替换
这与 sprintf() 类似,但使用单个替换标记并接受无限数量的参数。我相信有更好的方法可以做到这一点,但请原谅我的笨拙并尝试专注于它背后的想法。
Like before, you create a reusable function:
像以前一样,您创建了一个可重用的函数:
function fill(){
$arr = func_get_args(); $s = $arr[ 0 ]; array_shift( $arr );
while( strpos( $s, '/' ) !== false ){
$s = implode( current( $arr ), explode( '/', $s, 2 ) ); next( $arr );
} return $s;
}
Then call it from any scope:
然后从任何范围调用它:
$s = fill( 'I need to buy /, /, and / from the store.', BREAD, EGGS, MILK );
You can use any replacement token you want, like a % or #. I used the slash here since it's a bit easier to type.
您可以使用任何您想要的替换标记,例如 % 或 #。我在这里使用了斜线,因为它更容易输入。

