当我使用下面的代码时,即使函数看起来格式良好,它也会抛出错误。(仅供参考,我还尝试了有效和静态前缀。
函数调用:
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();
}