简体   繁体   English

如何在PHP中通过变量调用静态函数?

[英]How do I call static functions by variable in PHP?

When I use the code below it throws an error even though the function looks well formed. 当我使用下面的代码时,即使函数看起来很好,也会抛出错误。 (FYI I also tried valid and static prefixes.) (仅供参考我也尝试过有效的静态前缀。)


Function call: 功能调用:

foreach ($this->errorList as $field => $error_msg) {
            // check for valid input and store cleaned vars
            $this->goodInput[$field] = Valid::__($field);
}

Result: 结果:

PHP Fatal error: Call to undefined function Valid::email() PHP致命错误:调用未定义的函数Valid :: email()


Code: 码:

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 '';
        }
    }
}

I assume you instantiate your class somewhere properly first right? 我假设你首先在某个地方实例化你的课程吗? Well it's best to check that a said method exists, and harness self:: . 那么最好检查一下所说的方法是否存在,并利用self:: Also, as @fusion3k said , better to return self::$name() . 另外, 正如@ fusion3k所说 ,最好还是返回self::$name() Here's an example of what you should be doing: 这是你应该做的一个例子:

public static function __($name) {
    if(method_exists(new self, $name)) {
        return self::$name();
    }
}

In all honesty, this isn't the best way for you to be doing it. 老实说,这不是你做这件事的最佳方式。 You should be looking into call_func_user_array() to manage this kind of implementation properly. 您应该调查call_func_user_array()以正确管理此类实现。 Allowing the parsing of arguments to called methods. 允许将参数解析为被调用的方法。

There is not any object created when you call an static function then Valid functions are not accessible. 调用静态函数时没有创建任何对象,则无法访问有效函数。 Try like this 试试这样吧

public static function __($name) { 
$valid = new Valid ();
return $valid::$name(); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM