Calling a static method from another static method: PHP Fatal error: Call to undefined function

StackOverflow https://stackoverflow.com/questions/23673333

문제

In a simple PHP script (a WordPress module) I have defined a class with several static methods:

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]);
        }
}

Unfortunately I have to prepend the string WP_City_Gender:: to all static method names - even when I call them from static methods.

Otherwise I get the compile error:

PHP Fatal error: Call to undefined function valid()

This seems unusual to me, because in other programming languages it is possible to call static methods from static methods without specifying the class name.

Is there maybe a nicer way here (using PHP 5.3 on CentOS 6), to make my source code more readable?

도움이 되었습니까?

해결책

Indeed, like @hindmost said: Use self:: instead of WP_City_Gender::!

So for instance:

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 should have made that an answer :). Note that self is WITHOUT the dollar prefix ($), in contrast to $this which DOES have a dollar.

다른 팁

Use $this->valid() not WP_City_Gender::valid(); If it keeps giving you errors try changing the function from public static function to public function.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top