2013-01-01 98 views
-1

我想做一個類可以處理未定義變量的字符串。這可能嗎?或者,還有更好的方法?

舉例來說,如果我有以下的,並希望這一類的Looper採取$str_1並輸出與變量$fname$lname填寫了...然後在其他地方我可以重用尺蠖類和過程$str_2,因爲它們都需要$fname$lnamephp類傳入未定義的變量

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

回答

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