PHP: Variable in a function name

后端 未结 7 1855
有刺的猬
有刺的猬 2020-12-09 16:57

I want to trigger a function based on a variable.

function sound_dog() { return \'woof\'; }
function sound_cow() { return \'moo\'; }

$animal = \'cow\';
print soun         


        
相关标签:
7条回答
  • 2020-12-09 17:23

    You can use curly brackets to build your function name. Not sure of backwards compatibility, but at least PHP 7+ can do it.

    Here is my code when using Carbon to add or subtract time based on user chosen type (of 'add' or 'sub'):

    $type = $this->date->calculation_type; // 'add' or 'sub'
    
    $result = $this->contactFields[$this->date->{'base_date_field'}]
                       ->{$type.'Years'}( $this->date->{'calculation_years'} )
                       ->{$type.'Months'}( $this->date->{'calculation_months'} )
                       ->{$type.'Weeks'}( $this->date->{'calculation_weeks'} )
                       ->{$type.'Days'}( $this->date->{'calculation_days'} );
    

    The important part here is the {$type.'someString'} sections. This will generate the function name before executing it. So in the first case if the user has chosen 'add', {$type.'Years'} becomes addYears.

    0 讨论(0)
  • 2020-12-09 17:23

    You can use $this-> and self:: for class-functions. Example provided below with a function input-parameter.

    $var = 'some_class_function';
    call_user_func(array($this, $var), $inputValue); 
    // equivalent to: $this->some_class_function($inputValue);
    
    0 讨论(0)
  • 2020-12-09 17:28

    http://php.net/manual/en/functions.variable-functions.php

    To do your example, you'd do

    $animal_function = "sound_$animal";
    $animal_function();
    
    0 讨论(0)
  • 2020-12-09 17:30

    You should ask yourself why you need to be doing this, perhaps you need to refactor your code to something like the following:

    function animal_sound($type){ 
        $animals=array(); 
        $animals['dog'] = "woof"; 
        $animals['cow'] = "moo"; 
        return $animals[$type];
    }
    
    $animal = "cow";
    print animal_sound($animal);
    
    0 讨论(0)
  • 2020-12-09 17:36

    You can do it like this:

    $animal = 'cow';
    $sounder = "sound_$animal";
    print ${sounder}();
    

    However, a much better way would be to use an array:

    $sounds = array('dog' => sound_dog, 'cow' => sound_cow);
    
    $animal = 'cow';
    print $sounds[$animal]();
    

    One of the advantages of the array method is that when you come back to your code six months later and wonder "gee, where is this sound_cow function used?" you can answer that question with a simple text search instead of having to follow all the logic that creates variable function names on the fly.

    0 讨论(0)
  • 2020-12-09 17:36

    For PHP >= 7 you can use this way:

    function sound_dog() { return 'woof'; }
    function sound_cow() { return 'moo'; }
    
    $animal = 'cow';
    print ('sound_' . $animal)();
    
    0 讨论(0)
提交回复
热议问题