I want to trigger a function based on a variable.
function sound_dog() { return \'woof\'; } function sound_cow() { return \'moo\'; } $animal = \'cow\'; print soun
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
.