[英]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: 在一个简单的PHP脚本 (一个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]);
}
}
Unfortunately I have to prepend the string WP_City_Gender::
to all static method names - even when I call them from static methods. 不幸的是,我必须在所有静态方法名称前加上字符串WP_City_Gender::
-即使是从静态方法调用它们时也是如此。
Otherwise I get the compile error: 否则,我得到编译错误:
PHP Fatal error: Call to undefined function valid() PHP致命错误:调用未定义的函数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? 是否有更好的方法(在CentOS 6上使用PHP 5.3)使我的源代码更具可读性?
Indeed, like @hindmost said: Use self::
instead of WP_City_Gender::
! 确实,就像@hindmost所说:使用self::
而不是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. 请注意, self
是没有美元前缀($)的,而$this
确实有美元。
Use $this->valid() not WP_City_Gender::valid(); 使用$ this-> valid()而不是WP_City_Gender :: valid(); If it keeps giving you errors try changing the function from public static function to public function. 如果它仍然给您错误,请尝试将功能从public static function更改为public function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.