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

时间:2014-05-15 08:45:48

标签: php wordpress wordpress-plugin static-methods php-5.3

在一个简单的PHP script(一个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]);
        }
}

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

否则我收到编译错误:

  

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

这对我来说似乎不太常见,因为在其他编程语言中,可以从静态方法调用静态方法而无需指定类名。

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

2 个答案:

答案 0 :(得分:3)

确实,像@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]))
        ...
    }
}

Hindmost应该做出答案:)。请注意,self没有美元前缀($),而$this则有一美元。

答案 1 :(得分:-2)

使用$ this-> valid()而不是WP_City_Gender :: valid();如果它一直给你错误,请尝试将函数从公共静态函数更改为公共函数。

相关问题