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

发布于 2024-08-20 11:57:02 字数 131 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

_失温 2024-08-27 11:57:03

有趣的是,您可以使用关键字“const”作为函数的名称,以防止名称空间乱放:

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

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

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

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

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

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'] = function($a){return $a;};

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

简美 2024-08-27 11:57:03

聚会迟到了,但如果你不喜欢 (s)printf ,这是我的解决方案:

// Can of course be replaced with the const syntax
define("FOO", "bar");
$replace_pairs = ["%myConstant" => FOO];
// Output : "My constant : bar"
echo strtr("My constant : %myConstant", $replace_pairs);

Late to the party but here's my solution in case you don't like (s)printf :

// Can of course be replaced with the const syntax
define("FOO", "bar");
$replace_pairs = ["%myConstant" => FOO];
// Output : "My constant : bar"
echo strtr("My constant : %myConstant", $replace_pairs);
只有影子陪我不离不弃 2024-08-27 11:57:03

这是一个老问题,但对于那些在这里搜索的人来说,这是另一种方法

<?php
define( 'MY_CONSTANT', 'world' );

echo "Hello {${$constant = 'constant'}('MY_CONSTANT')}";

This is an old question but for those searching here is another way to do it

<?php
define( 'MY_CONSTANT', 'world' );

echo "Hello {${$constant = 'constant'}('MY_CONSTANT')}";
梦里寻她 2024-08-27 11:57:03

我经常需要它,主要是在编写脚本时,打印新行字符。
从浏览器运行脚本时,换行符应该是
而从终端执行脚本时,它应该是 PHP_EOL

所以,我做了类似的事情:

$isCLI = ( php_sapi_name() == 'cli' );
$eol = $isCLI ? PHP_EOL : '<br>'; 
echo "${eol} This is going to be printed in a new line";

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 be PHP_EOL

So, I do something like:

$isCLI = ( php_sapi_name() == 'cli' );
$eol = $isCLI ? PHP_EOL : '<br>'; 
echo "${eol} This is going to be printed in a new line";
朱染 2024-08-27 11:57:03

我相信这回答了OP最初的问题。唯一的事情是全局索引键似乎只能以小写形式工作。

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

输出:

DB_USER=root

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

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

Output:

DB_USER=root
森末i 2024-08-27 11:57:02

不。

对于字符串,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

瞎闹 2024-08-27 11:57:02

是的,它是(在某种程度上;)):

define('FOO', 'bar');

$test_string = sprintf('This is a %s test string', FOO);

这可能不是您想要的,但我认为,从技术上讲,这不是连接,而是替换,并且从这个假设来看,它在字符串中包含一个常量而不连接。

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.

夏花。依旧 2024-08-27 11:57:02

要在字符串中使用常量,您可以[1]使用以下方法:

define( 'ANIMAL', 'turtles' ); 
$constant = constant(...);
echo "I like {$constant('ANIMAL')}!";

[1]“可以”并不意味着你“应该”,实际上我建议你实际上这样做:

sprintf('我喜欢 %s!', ANIMAL);



如何{$constant('ANIMAL')} 有效吗?

字符串内的 {} 括号允许我们调用任何以 $ 开头的可调用函数!

"I like {constant('ANIMAL')}"; 没有 $不会触发变量替换,因此我们必须将可调用对象放入一个变量。

顺便说一下:constant(...) 语法称为 第一类可调用语法

您还可以使用字符串函数名称 - 和任意参数

可以将任何函数名称放入变量中,并使用双引号字符串内的参数调用它。也适用于多个参数。

$fn = 'substr';

echo "I like {$fn('turtles!', 0, -1)}";

生产

我喜欢乌龟

还有匿名函数、数组等

$escape = fn( $string ) => htmlspecialchars( (string) $string, ENT_QUOTES, 'utf-8' );
$userText = "<script>alert('xss')</script>";

echo "You entered {$escape( $userText )}";

产生:

您输入了<script>alert('xss')</script>

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

echo "I like {$fn(['turtles'], 0)}!"; 

生产:

我喜欢乌龟!

在 3v4l.org 上亲自尝试 并注意 - 大多数可调用类型(除了 string< /code>)在 php5.3 之前不起作用(在最初撰写这篇文章的时间) - 现在更新到 php7++ 时代

请记住,

这种做法是不明智的,但可能性是存在的。

To use constants inside strings you can[1] use the following approach:

define( 'ANIMAL', 'turtles' ); 
$constant = constant(...);
echo "I like {$constant('ANIMAL')}!";

[1] "can" does not mean you "should", practically I advise you actually do this:

sprintf('I like %s!', ANIMAL);



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.

$fn = 'substr';

echo "I like {$fn('turtles!', 0, -1)}";

Produces

I like turtles

Also anonymous functions, arrays etc

$escape = fn( $string ) => htmlspecialchars( (string) $string, ENT_QUOTES, 'utf-8' );
$userText = "<script>alert('xss')</script>";

echo "You entered {$escape( $userText )}";

Produces:

You entered <script>alert('xss')</script>

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

echo "I like {$fn(['turtles'], 0)}!"; 

Produces:

I like turtles!

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+++ era

Keep in mind

This practice is ill-advised, but the possibility is there.

花间憩 2024-08-27 11:57:02
define( 'FOO', 'bar');  
$FOO = FOO;  
$string = "I am too lazy to concatenate $FOO in my string";
define( 'FOO', 'bar');  
$FOO = FOO;  
$string = "I am too lazy to concatenate $FOO in my string";
红衣飘飘貌似仙 2024-08-27 11:57:02
define('FOO', 'bar');
$constants = create_function('$a', 'return $a;');
echo "Hello, my name is {$constants(FOO)}";
define('FOO', 'bar');
$constants = create_function('$a', 'return $a;');
echo "Hello, my name is {$constants(FOO)}";
我不咬妳我踢妳 2024-08-27 11:57:02

如果您确实想要在不连接的情况下回显常量,这里是解决方案:

define('MY_CONST', 300);
echo 'here: ', MY_CONST, ' is a number';

注意:在此示例中,echo 需要多个参数(查看逗号 ),所以它不是真正的串联

Echo 表现为一个函数,它需要更多的参数,它比串联更高效,因为它不需要串联然后回显,它只是回显所有内容,而不需要创建新的字符串连接对象:))

编辑

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

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

独留℉清风醉 2024-08-27 11:57:02

你可以这样做:

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

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']}";
鼻尖触碰 2024-08-27 11:57:02

最简单的方法是

define('MY_CONSTANT', 42);

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

使用 (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;

The easiest way is

define('MY_CONSTANT', 42);

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

Another way using (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;
太阳哥哥 2024-08-27 11:57:02

正如其他人指出的那样,你不能这样做。 PHP 有一个函数 constant() ,它不能直接在字符串中调用,但我们可以轻松解决这个问题。

$constant = function($cons){
   return constant($cons);
};

及其用法的基本示例:

define('FOO', 'Hello World!');
echo "The string says {$constant('FOO')}"; 

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.

$constant = function($cons){
   return constant($cons);
};

and a basic example on its usage:

define('FOO', 'Hello World!');
echo "The string says {$constant('FOO')}"; 
远山浅 2024-08-27 11:57:02

以下是其他答案的一些替代方案,这些答案似乎主要集中在“{$}”技巧上。尽管无法保证其速度;这都是纯粹的语法糖。对于这些示例,我们假设定义了下面的一组常量。

define( 'BREAD', 'bread' ); define( 'EGGS', 'eggs' ); define( 'MILK', 'milk' );

使用 extract()
这个很好,因为结果与变量相同。首先,您创建一个可重用的函数:

function constants(){ return array_change_key_case( get_defined_constants( true )[ 'user' ] ); }

然后从任何范围调用它:

extract( constants() );
$s = "I need to buy $bread, $eggs, and $milk from the store.";

在这里,它将常量小写以便于您的手指操作,但您可以删除 array_change_key_case() 以保持它们原样。如果您已经有冲突的局部变量名称,则常量不会覆盖它们。

使用字符串替换
这与 sprintf() 类似,但使用单个替换标记并接受无限数量的参数。我确信有更好的方法可以做到这一点,但请原谅我的笨拙并尝试专注于其背后的想法。

像以前一样,您创建一个可重用函数:

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

然后从任何范围调用它:

$s = fill( 'I need to buy /, /, and / from the store.', BREAD, EGGS, MILK );

您可以使用您想要的任何替换标记,例如 % 或 #。我在这里使用了斜杠,因为它更容易输入。

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:

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.

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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文