[英]How do I call static functions by variable in PHP?
當我使用下面的代碼時,即使函數看起來很好,也會拋出錯誤。 (僅供參考我也嘗試過有效的靜態前綴。)
功能調用:
foreach ($this->errorList as $field => $error_msg) {
// check for valid input and store cleaned vars
$this->goodInput[$field] = Valid::__($field);
}
結果:
PHP致命錯誤:調用未定義的函數Valid :: email()
碼:
class Valid
{
public static function __($name)
{
// this is what I tried:
// $checkFunction = 'self::' . $name;
// return $checkFunction();
// this works:
// Thank you to fusion3k and Darren
return self::$name();
}
private static function email()
{
//sanitize and validate email field
}
// other methods for other fields
// ...
// default method to sanitize input for display in email
public static function __callStatic($name, $arguments)
{
if (array_key_exists($name, $_POST)) {
$clean_var = trim($_POST[$name]);
$clean_var = stripslashes($clean_var);
$clean_var = htmlspecialchars($clean_var);
return $clean_var;
} else {
return '';
}
}
}
我假設你首先在某個地方實例化你的課程嗎? 那么最好檢查一下所說的方法是否存在,並利用self::
。 另外, 正如@ fusion3k所說 ,最好還是返回self::$name()
。 這是你應該做的一個例子:
public static function __($name) {
if(method_exists(new self, $name)) {
return self::$name();
}
}
老實說,這不是你做這件事的最佳方式。 您應該調查call_func_user_array()
以正確管理此類實現。 允許將參數解析為被調用的方法。
調用靜態函數時沒有創建任何對象,則無法訪問有效函數。 試試這樣吧
public static function __($name) {
$valid = new Valid ();
return $valid::$name();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.