全局命名空间函数在命名空间类构造函数中不可用



WordPress具有全局函数,例如wp_get_current_user((,我可以在具有wp_get_current_user的不同命名空间下的类方法中调用它们。但是,我无法在类构造函数中执行此操作或将其设置为变量(类属性,例如 $user = wp_get_current_user (。我猜这里有一个我不知道的 PHP 规则?

例如

namespace App;
class User{
    //this doesn't work **I found that this is because we have to initialize the variables with constants (expressions aren't allowed**
    $user = wp_get_current_user(); 
    function __construct(){
        //this also doesn't work
        $this->user = wp_get_current_user();
        $this->init();
    }
    function init(){
        //this works
        $this->user = wp_get_current_user();
    }
}

wp_get_current_user(( 是/wp-include/pluggable.php 中的可插拔函数,您可以将其用作函数调用,如下所示:

<?php $current_user = wp_get_current_user(); ?>

也许您可以从全局上下文调用 wp_get_current_user((,并将其值作为参数传递给 User 类构造函数。然后,您应该能够从类中访问当前用户

所以无法在插件构造函数中调用此方法的原因是wp_get_current_user(( 是在可插拔.php文件中定义的(如果我们选择,可以覆盖其中的函数(,该文件在所有插件之后加载。因此,解决方案是在注册到WordPress钩子(add_action,.(的类方法中调用此函数。过滤器(。

最新更新