1
foreach($arr as $el){
    $what= $el->what;
    if($what == 'img'){get_img();}
    elseif($what == 'video'){get_video();
    elseif($what == 'something'){get_something();} 
}

How to say the above shortly, like this:

 get_$what();

4 Answers 4

2

as in https://www.php.net/manual/en/functions.variable-functions.php

$func = 'foo';
$func();        // This calls foo()

so in your case:

foreach($arr as $el){
    $what= $el->what;
    $funcname = 'get_'.$what;
    $funcname();
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use parentheses

<?php

function ab(){echo 'ho';}
$foo='video';
('get_'.$foo)();

1 Comment

I already answered this question once. If I could only find where.
1

You could save the function name into a variable and then call that function dynamically by adding () to the variable. ( not sure if i said this right )

$yourFunction = 'get_';
$yourFunction .= 'img';

$value = $yourFunction();
// will execute get_img();

here is a fiddle to play with

Comments

1
 function get_id(){
        echo "id";
       }
    function get_d(){
        echo "d";
        }

      $id='id';
      $fun='get_'.$id;
      $fun();

outputs: id

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.