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

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.

Read More

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?

Related posts

Leave a Reply

2 comments

  1. 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.

  2. 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.