我试图将多个参数传递给包含sprintf()方法的自定义方法.我传递的参数将在sprintf()方法中使用.有没有办法做到这一点?我尝试了下面的代码,但得到"太少的论点".
<?php
function myMethod($text, $args)
{
echo sprintf($text, $args);
}
myMethod('"%s" is "%s" method', 'This', 'my');
?>
Run Code Online (Sandbox Code Playgroud)
使用vsprintf()而不是sprintf()是任何解决方案的核心,因为您将参数作为数组传递:
如果您使用的是PHP 5.6,并且可以使用可变参数
function myMethod($text, ...$args)
{
echo vsprintf($text, $args);
}
myMethod('"%s" is "%s" method', 'This', 'my');
Run Code Online (Sandbox Code Playgroud)
否则func_get_args()是你的朋友:
function myMethod($text)
{
$args = func_get_args();
array_shift($args); // remove $text argument from the $args array
echo vsprintf($text, $args);
}
myMethod('"%s" is "%s" method', 'This', 'my');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
434 次 |
| 最近记录: |