我多次调用此函数,传递$ case的额外参数,告诉我调用此函数的时间:
function check($chars,$case=1){
$charNums = array(
"a" => "2",
"b" => "22",
"c" => "222",
"d" => "3",
"e" => "33",
"f" => "333",
"g" => "4",
"h" => "44",
"i" => "444",
"j" => "5",
"k" => "55",
"l" => "555",
"m" => "6",
"n" => "66",
"o" => "666",
"p" => "7",
"q" => "77",
"r" => "777",
"s" => "7777",
"t" => "8",
"u" => "88",
"v" => "888",
"w" => "9",
"x" => "99",
"y" => "999",
"z" => "9999",
" " => "0",
);
echo "Case #{$case}: ";
for($i=0;$i<strlen($chars);$i++){
if($prevChar == $charNums[$chars[$i]][0]) echo " ";
echo $charNums[$chars[$i]];
$prevChar = $charNums[$chars[$i]][0];
}
echo "<br>";
}
我想让这个函数自己计算它被调用的次数。为了节省额外的参数成本,我看到每个javascript函数都有自己的默认属性。
答案 0 :(得分:2)
使用静态变量:
function check($chars){
static $count = 0;
++$count;
// TODO: your implementation here
return $count;
}
如果您已将返回值用于其他目的,则可以将该函数包装在类中:
class Checker {
public static $count = 0;
public static function check($chars) {
++self::$count;
// TODO: your implementation here
return $whatever;
}
}
答案 1 :(得分:0)
你没有解读
$ prevChar
用于匹配for循环...
使用此
for($i=0;$i<strlen($chars);$i++){
$prevChar = $chars[$i];
if($prevChar == $charNums[$chars[$i]][0]) echo " ";
echo $charNums[$chars[$i]];
$prevChar = $charNums[$chars[$i]][0];
}