以下是其他答案的一些替代方法,它们似乎主要集中在“{$}”技巧上。尽管不能保证它们的速度;这都是纯语法糖。对于这些示例,我们假设定义了以下常量集。
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 );
您可以使用任何您想要的替换标记,例如 % 或 #。我在这里使用了斜线,因为它更容易输入。