PHP: Variable in a function name

后端 未结 7 1871
有刺的猬
有刺的猬 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.

提交回复
热议问题