在字符串中包含常量而不连接

时间:2022-10-26 17:00:10

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";

12 个解决方案

#1


114  

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()是获取常量的另一种方式,但是如果不进行连接,函数调用也不能放入字符串中。

Manual on constants in PHP

关于PHP中的常量的手册

#2


88  

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.

这可能不是你想要的,但我认为,从技术上讲,这不是连接,而是一个替换,从这个假设,它包含了一个没有连接的常量。

#3


44  

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_callable would cause a fatal error when used inside a string:

如果现在您的印象是函数名可以是任何可调用的,那就不是这样了,当一个数组在传递给is_callable时返回true,当在字符串中使用时,它会导致一个致命错误:

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.

这种做法是不明智的,但有时会产生更容易读懂的代码,所以这取决于您——这种可能性是存在的。

#4


17  

define( 'FOO', 'bar');  
$FOO = FOO;  
$string = "I am too lazy to concatenate $FOO in my string";

#5


13  

define('FOO', 'bar');
$constants = create_function('$a', 'return $a;');
echo "Hello, my name is {$constants(FOO)}";

#6


11  

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']}";

#7


10  

If you really want to echo constant without concatenation here 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作为一个函数,它需要更多的参数,它比连接更高效,因为它不需要先连接然后Echo,它只对所有东西进行响应,不需要创建新的字符串连接对象:)

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..

另外,如果考虑将字符串连接起来,将字符串传递为参数,或者使用“,(逗号版本)总是最快的,接下来。(连接“单引号”)和最慢的字符串构建方法是使用双引号”,因为这样写的表达式必须根据声明的变量和函数进行计算。

#8


5  

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')}"; 

#9


1  

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.

您可以使用任何您想要的替换令牌,如%或#。我在这里使用斜线,因为它更容易输入。

#10


1  

The easiest way is

最简单的方法是

define('MY_CONSTANT', 42);

$my_constant = MY_CONSTANT;
echo "This is my constant: $my_constant";

Another way using (s)printf

另一种方式使用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;

#11


0  

It is fun that you can use keyword 'const' as a name for your function to prevent namespace littering:

您可以使用关键字“const”作为函数的名称,以防止命名空间垃圾:

define("FOO","foo");
${'const'} = function($a){return $a;};
echo "{$const(FOO)}"; // Prints "foo"
echo const(FOO); // Parse error: syntax error, unexpected T_CONST

You can also use $GLOBALS to propagate 'const' function all over the code:

您还可以使用$GLOBALS在整个代码中传播“const”函数:

$GLOBALS['const'] = function($a){return $a;};

Unsure is it safe for future using. And what is worse - it's still looks ugly.

不确定是否安全,将来使用。更糟糕的是,它看起来仍然很丑。

#12


-2  

I believe this answers the OP's original question. The only thing is the globals index key seems to only work as lower case.

我相信这回答了OP最初的问题。唯一的问题是全局索引键似乎只起作用。

define('DB_USER','root');
echo "DB_USER=$GLOBALS[db_user]";

Output:

输出:

DB_USER=root

#1


114  

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()是获取常量的另一种方式,但是如果不进行连接,函数调用也不能放入字符串中。

Manual on constants in PHP

关于PHP中的常量的手册

#2


88  

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.

这可能不是你想要的,但我认为,从技术上讲,这不是连接,而是一个替换,从这个假设,它包含了一个没有连接的常量。

#3


44  

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_callable would cause a fatal error when used inside a string:

如果现在您的印象是函数名可以是任何可调用的,那就不是这样了,当一个数组在传递给is_callable时返回true,当在字符串中使用时,它会导致一个致命错误:

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.

这种做法是不明智的,但有时会产生更容易读懂的代码,所以这取决于您——这种可能性是存在的。

#4


17  

define( 'FOO', 'bar');  
$FOO = FOO;  
$string = "I am too lazy to concatenate $FOO in my string";

#5


13  

define('FOO', 'bar');
$constants = create_function('$a', 'return $a;');
echo "Hello, my name is {$constants(FOO)}";

#6


11  

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']}";

#7


10  

If you really want to echo constant without concatenation here 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作为一个函数,它需要更多的参数,它比连接更高效,因为它不需要先连接然后Echo,它只对所有东西进行响应,不需要创建新的字符串连接对象:)

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..

另外,如果考虑将字符串连接起来,将字符串传递为参数,或者使用“,(逗号版本)总是最快的,接下来。(连接“单引号”)和最慢的字符串构建方法是使用双引号”,因为这样写的表达式必须根据声明的变量和函数进行计算。

#8


5  

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')}"; 

#9


1  

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.

您可以使用任何您想要的替换令牌,如%或#。我在这里使用斜线,因为它更容易输入。

#10


1  

The easiest way is

最简单的方法是

define('MY_CONSTANT', 42);

$my_constant = MY_CONSTANT;
echo "This is my constant: $my_constant";

Another way using (s)printf

另一种方式使用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;

#11


0  

It is fun that you can use keyword 'const' as a name for your function to prevent namespace littering:

您可以使用关键字“const”作为函数的名称,以防止命名空间垃圾:

define("FOO","foo");
${'const'} = function($a){return $a;};
echo "{$const(FOO)}"; // Prints "foo"
echo const(FOO); // Parse error: syntax error, unexpected T_CONST

You can also use $GLOBALS to propagate 'const' function all over the code:

您还可以使用$GLOBALS在整个代码中传播“const”函数:

$GLOBALS['const'] = function($a){return $a;};

Unsure is it safe for future using. And what is worse - it's still looks ugly.

不确定是否安全,将来使用。更糟糕的是,它看起来仍然很丑。

#12


-2  

I believe this answers the OP's original question. The only thing is the globals index key seems to only work as lower case.

我相信这回答了OP最初的问题。唯一的问题是全局索引键似乎只起作用。

define('DB_USER','root');
echo "DB_USER=$GLOBALS[db_user]";

Output:

输出:

DB_USER=root