从另一个静态方法调用一个静态方法:PHP 致命错误:调用未定义的函数

Ale*_*ber 3 php wordpress static-methods php-5.3

在一个简单的PHP 脚本(一个 WordPress 模块)中,我定义了一个包含几个静态方法的类:

class WP_City_Gender {

        public static function valid($str) {
                return (isset($str) && strlen($str) > 0);
        }

        public static function fix($str) {
                return (WP_City_Gender::valid($str) ? $str : '');
        }

        public static function user_register($user_id) {
                if (WP_City_Gender::valid($_POST[FIRST_NAME]))
                        update_user_meta($user_id, FIRST_NAME, $_POST[FIRST_NAME]);
                if (WP_City_Gender::valid($_POST[LAST_NAME]))
                        update_user_meta($user_id, LAST_NAME, $_POST[LAST_NAME]);
                if (WP_City_Gender::valid($_POST[GENDER]))
                        update_user_meta($user_id, GENDER, $_POST[GENDER]);
                if (WP_City_Gender::valid($_POST[CITY]))
                        update_user_meta($user_id, CITY, $_POST[CITY]);
        }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我必须将字符串添加WP_City_Gender::到所有静态方法名称之前 - 即使我从静态方法调用它们也是如此。

否则我会收到编译错误:

PHP 致命错误:调用未定义的函数 valid()

这对我来说似乎不寻常,因为在其他编程语言中,可以在不指定类名的情况下从静态方法调用静态方法。

这里有没有更好的方法(在 CentOS 6 上使用 PHP 5.3),使我的源代码更具可读性?

Bar*_*art 5

确实,就像@hindmost 所说的:使用self::而不是WP_City_Gender::!

所以例如:

class WP_City_Gender {
....
    public static function valid($str) {
        return (isset($str) && strlen($str) > 0);
    }
    ...
    public static function user_register($user_id) {
        if (self::valid($_POST[FIRST_NAME]))
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

Hindmost 应该已经回答了:)。请注意,self没有美元前缀 ($),$this而 DOES 有美元前缀。