我正在尝试创建一个可以使用未定义的变量处理字符串的类。这可能吗?还是有更好的方法?
例如,如果我有以下内容并希望此类Looper采用$str_1
并输出变量$fname
和$lname
填充...那么在其他地方我可以重用Looper类和进程$str_2
因为它们都需要$fname
和$lname
。
class Looper {
public function processLoop($str){
$s='';
$i=0;
while ($i < 4){
$fname = 'f' . $i;
$lname = 'l' . $i;
$s .= $str . '<br />';
$i++;
}
return $s;
}
}
$str_1 = "First Name: $fname, Last Name: $lname";
$rl = new Looper;
print $rl->processLoop($str_1);
$str_2 = "Lorem Ipsum $fname $lname is simply dummy text of the printing and typesetting industry";
print $rl->processLoop($str_2);
答案 0 :(得分:2)
为什么不使用strtr
:
$str_1 = "First Name: %fname%, Last Name: %lname%";
echo strtr($str_1, array('%fname%' => $fname, '%lname%' => $lname));
所以在上下文中你的班级:
public function processLoop($str){
$s='';
$i=0;
while ($i < 4){
$tokens = array('%fname%' => 'f' . $i, '%lname%' => 'l' . $i);
$s .= strtr($str, $tokens) . '<br />';
$i++;
}
return $s;
}
同样,如果您不想依赖于命名占位符,则可以通过sprintf
使用位置占位符:
public function processLoop($str){
$s='';
$i=0;
while ($i < 4){
$s .= sprintf($str, 'f' . $i, l' . $i) . '<br />';
$i++;
}
return $s;
}
在这种情况下,您的$str
参数看起来像"First Name: %s, Last Name: %s"
所有用法:
// with strtr
$str_1 = "First Name: %fname%, Last Name: %lname%";
$rl = new Looper;
print $rl->processLoop($str_1);
// with sprintf
$str_1 = "First Name: %s, Last Name: %s";
$rl = new Looper;
print $rl->processLoop($str_1);