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

时间:2016-11-15 15:40:23

标签: php oop

我有下课。

    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)上出现上述错误。我正在使用基于角色的访问控制。

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:2)

静态对象和函数无权访问$this。如果您使用$user = new User()创建此广告,则需要使用__construct()方法更改通话:

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

有关静态vs实例化类的更多信息,请参见this question

修改正如simon提醒我的那样,该功能本身也需要删除static关键字。

答案 1 :(得分:1)

你正在使用$ this,但你是外面的对象。 受保护的静态函数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)删除static keyword:

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"]); 
    }
} 

}