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?

2 Answers 2

11

have you tried this?

foreach ($this->cron_hooks as $name => $options) {
    echo "Hook '$name' will run every ${$options['frequency']} seconds.";    
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's ${options['frequency']}, right?
8

Try:

${options['frequency']}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.