OOP致命错误:不在对象上下文中使用$this


OOP Fatal error: Using $this when not in object context

我有以下类。

    class User 
    {
        private $userRoles = array();
        //Populate the user object when it's created
        public function __construct($dbConn,$user_id)
        {
                self::loadRoles($dbConn,$user_id);//Initiate the userroles
        }
        //Fill the array with this user's roles, it's
        protected static function loadRoles($dbConn,$user_id)
        {
            $fetchRoles = $dbConn->prepare("SELECT tbl_user_role.role_id, tbl_roles.role_name FROM tbl_user_role JOIN tbl_roles ON tbl_user_role.role_id = tbl_roles.id WHERE tbl_user_role.user_id = :user_id");
            $fetchRoles->bindParam(':user_id', $user_id);
            $fetchRoles->execute();
                    //Populate the array
            while($row = $fetchRoles->fetch(PDO::FETCH_ASSOC))
            {
                $this->userRoles[$row["role_name"]] = Role::getRole($dbConn,$row["role_id"]); 
(Fatal error: Using $this when not in object context.)
            }
        } 
    }

在这个function protected static function loadRoles($dbConn,$user_id)上得到以上错误。我正在与基于角色的访问控制工作。

请帮帮我。

静态对象和函数不能访问$this。如果您使用$user = new User()创建这个,那么您需要更改__construct()方法中的调用:

public function __construct($dbConn,$user_id)
{
    $this->loadRoles($dbConn,$user_id);//Initiate the userroles
}

关于静态类和实例化类的更多信息可以在这个问题中找到。

Edit正如simon提醒我的,函数本身也需要删除static关键字。

您正在使用$this,但您是外部对象。protected static function loadRoles($dbConn,$user_id)静态函数不会在对象中执行,所以你有2个机会:1)返回角色,然后做任何你想做的事情:

$roles = array();
while($row = $fetchRoles->fetch(PDO::FETCH_ASSOC))
{
    $roles[$row["role_name"]] = Role::getRole($dbConn,$row["role_id"]); 
}
2)删除静态关键字:
class User {
private $userRoles = array();
//Populate the user object when it's created
public function __construct($dbConn,$user_id)
{
    $this->loadRoles($dbConn,$user_id);//Initiate the userroles
}
//Fill the array with this user's roles, it's
protected function loadRoles($dbConn,$user_id)
{
    $fetchRoles = $dbConn->prepare("SELECT tbl_user_role.role_id, tbl_roles.role_name FROM tbl_user_role JOIN tbl_roles ON tbl_user_role.role_id = tbl_roles.id WHERE tbl_user_role.user_id = :user_id");
    $fetchRoles->bindParam(':user_id', $user_id);
    $fetchRoles->execute();
            //Populate the array
    while($row = $fetchRoles->fetch(PDO::FETCH_ASSOC))
    {
        $this->userRoles[$row["role_name"]] = Role::getRole($dbConn,$row["role_id"]); 
    }
} 

}