簡體   English   中英

PHP:函數名中的變量

[英]PHP: Variable in a function name

我想基於變量觸發一個函數。

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

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

*行是不正確的行。

我以前做過這個,但我找不到它。 我知道潛在的安全問題等。

任何人? 非常感謝。

你可以這樣做,但不能沒有先插入字符串:

$animfunc = 'sound_' . $animal;
print $animfunc();

或者,使用call_user_func()跳過臨時變量:

call_user_func('sound_' . $animal);

你可以這樣做:

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

但是,更好的方法是使用數組:

$sounds = array('dog' => sound_dog, 'cow' => sound_cow);

$animal = 'cow';
print $sounds[$animal]();

數組方法的一個優點是,當你六個月后回到你的代碼並想知道“gee,這個sound_cow函數在哪里使用?” 您可以使用簡單的文本搜索來回答該問題,而不必遵循動態創建變量函數名稱的所有邏輯。

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

舉個例子,你做的

$animal_function = "sound_$animal";
$animal_function();

您應該問自己為什么需要這樣做,也許您需要將代碼重構為以下內容:

function animal_sound($type){ 
    $animals=array(); 
    $animals['dog'] = "woof"; 
    $animals['cow'] = "moo"; 
    return $animals[$type];
}

$animal = "cow";
print animal_sound($animal);

您可以使用$this->self:: for class-functions。 下面提供了一個帶有函數輸入參數的示例。

$var = 'some_class_function';
call_user_func(array($this, $var), $inputValue); 
// equivalent to: $this->some_class_function($inputValue);

您可以使用花括號來構建函數名稱。 不確定向后兼容性,但至少PHP 7+可以做到這一點。

這是我使用Carbon根據用戶選擇的類型('add'或'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'} );

這里重要的部分是{$type.'someString'}部分。 這將在執行之前生成函數名稱。 因此,在第一種情況下,如果用戶選擇了“添加”,則{$type.'Years'}將成為addYears

對於PHP >= 7您可以使用以下方式:

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

$animal = 'cow';
print ('sound_' . $animal)();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM