6

I have an array of custom hooks I'd like to schedule, built along these lines:

public function __construct(WPSM_Logger $injected_logger = null) {
    $this->cron_hooks[WPSM_CRONHOOK_SENDQUEUE] = array ("frequency" => 60);
}

Then, in the constructur for my Scheduler class, I would like to loop through $this->cronhooks and schedule each hook in that array. I normally prefer straight and simple variable expansion within double quoted strings, like what I do with $name below, but I can't seem to figure out how to do this with an array and subscript.

foreach ($this->cron_hooks as $name => $options) {
    $freq = $options["frequency"];
    echo "Hook '$name' will run every $freq seconds.";  
}

I would like to do away with the intermediary $freq = $options["frequency"]; line, and have something like this in the echo line:

foreach ($this->cron_hooks as $name => $options) {
    $freq = $options["frequency"];
    echo "Hook '$name' will run every $options['frequency]seconds.";    
}

However, I simply can't get that to work. Is there something special I'm missing, or do I really have to drag an extra variable along to my party?

hakre
  • 193,403
  • 52
  • 435
  • 836
ProfK
  • 49,207
  • 121
  • 399
  • 775

2 Answers2

11

have you tried this?

foreach ($this->cron_hooks as $name => $options) {
    echo "Hook '$name' will run every ${$options['frequency']} seconds.";    
}
Alex
  • 7,538
  • 23
  • 84
  • 152
8

Try:

${options['frequency']}

See: https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

Dexygen
  • 12,287
  • 13
  • 80
  • 147