Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP array of functions: interpreter unexpectedly calls all functions during evaluation of the array

I have this little helper method here:

private function continueConv($attribute, $next): void
{
    $sequence = [   $this->askName(),
                    $this->askEmail(),
                    $this->askPhone(),
                    $this->manageMessage()
                ];

    match($attribute) {
        'user_name' => $sequence[0 + (int)$next], 
        'user_email' => $sequence[1 + (int)$next], 
        'user_phone' => $sequence[2 + (int)$next]
    };

    return;
}

When the interpreter evaluates the $sequence array, instead of just storing the pointers to those functions, it calls them all!
Is this a bug?
Are there working alternatives?
Thanks


EDIT:
alternative approach that works:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

private function continueConv($attribute, $next): void
{

    match($attribute) {
        'user_name' => $next ? $this->askEmail() : $this->askName(), 
        'user_email' => $next ? $this->askPhone() : $this->askEmail(), 
        'user_phone' => $next ? $this->manageMessage() : $this->askPhone()
    };

    return;
}

but I’d prefer to use an array of functions in order to easily change the sequence.

>Solution :

You can use an array containing the object and method name as a callable. So just put the method names in the array.

private function continueConv($attribute, $next): void
{
    $sequence = ['askName', 'askEmail', 'askPhone', 'manageMessage'];

    $func = [$this, match($attribute) {
        'user_name' => $sequence[0 + $next], 
        'user_email' => $sequence[1 + $next], 
        'user_phone' => $sequence[2 + $next]
    }];

    $func();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading