Reputation: 4534
I am calling this function multiple times, passing extra parameter of $case which tells me how many time this function is called:
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>";
}
I want this function to count itself how many times it is called. To save the extra parameter cost, I have seen that each javascript function have its own default attributes.
Upvotes: 0
Views: 1278
Reputation: 31675
Use a static variable:
function check($chars){
static $count = 0;
++$count;
// TODO: your implementation here
return $count;
}
If you already use the return value for some other purpose, you can wrap the function in a class:
class Checker {
public static $count = 0;
public static function check($chars) {
++self::$count;
// TODO: your implementation here
return $whatever;
}
}
Upvotes: 2
Reputation: 1140
You did not declear
$prevChar
for matching in for loop...
Use this
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];
}
Upvotes: 0