在字符串中包含常量而不进行串联

PHP中有没有一种方法可以在字符串中包含常量而不进行串联?


define('MY_CONSTANT', 42);


echo "This is my constant: MY_CONSTANT";


交互式爱情
浏览 322回答 3
3回答

月关宝盒

没有。使用字符串,除了常量标识符外,PHP无法分辨字符串数据。这适用于PHP中的任何字符串格式,包括heredoc。constant() 是获取常量的另一种方法,但是没有连接也不能将函数调用放入字符串中。

慕容森

要在字符串中使用常量,可以使用以下方法:define( 'ANIMAL', 'turtles' );&nbsp;$constant = 'constant';echo "I like {$constant('ANIMAL')}";这是如何运作的?您可以使用任何字符串函数名称和任意参数可以将任何函数名称放在变量中,并在双引号字符串内用参数调用它。也可以使用多个参数。$fn = 'substr';echo "I like {$fn('turtles!', 0, -1)}";产生我喜欢乌龟也是匿名功能如果您正在运行PHP 5.3+,则还可以使用匿名函数。$escape&nbsp; &nbsp;= function ( $string ) {&nbsp; &nbsp; return htmlspecialchars( (string) $string, ENT_QUOTES, 'utf-8' );};$userText = "<script>alert('xss')</script>";echo( "You entered {$escape( $userText )}" );按预期产生正确转义的html。不允许使用回调数组!如果到现在为止,您对函数名称可以是任何可调用的印象都是这样,那么情况并非如此,因为在传递给is_callable字符串时返回true的数组在字符串中使用时将导致致命错误:class Arr{&nbsp; &nbsp; public static function get( $array, $key, $default = null )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return is_array( $array ) && array_key_exists( $key, $array )&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? $array[$key]&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : $default;&nbsp; &nbsp; }}$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 )}" );&nbsp;记住这种做法是不明智的,但有时会导致代码更具可读性,因此由您自己决定-存在这种可能性。
打开App,查看更多内容
随时随地看视频慕课网APP