I'm attempting to make an achievement system for a memorization website ("You memorized 50 cards," etc.), and the method I'm trying to use is an array of anonymous functions:
class AchievementController extends Controller
{
private static $rules = array(
'card'=>array(
1=>function() {
//do check for achievement
},
2=>function() {
//do check for achievement
}
),
'set'=>array(
5=>function() {
//do check for achievement
},
6=>function() {
//do check for achievement
},
)
);
//...
}
The idea is that certain types of rules for achievements will be checked at certain times, i.e. when you learn a new card, the card
subset will be checked. I had hoped to use a foreach
loop like this:
foreach(self::$rules[$type] as $rule)
{
$rule();
}
However, when I try to declare the $rules
array, I get this error:
PHP Parse error: syntax error, unexpected 'function' (T_FUNCTION) in
/.../controllers/achievement.php on line 24
If I declare $rules
inside a function (NOT static), it works just fine. I can't put it inside a constructor, because this class is being used statically, so no constructor will be called.
My question is, is it possible for me to do this in a static array? Or ought I just to do something else?
(Extra question: Is there a better way than this to do achievements?)