Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 920
Alexander Farber Avatar asked Apr 23 '26 18:04

Alexander Farber


1 Answers

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.

like image 124
Bart Avatar answered Apr 26 '26 09:04

Bart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!