3

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?

1
  • 7
    Use self:: instead of WP_City_Gender:: Commented May 15, 2014 at 8:47

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.