Vikas Badola Vikas Badola - 17 days ago 8
PHP Question

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

I have following class.

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.)
}
}
}


Getting above error on this
function protected static function loadRoles($dbConn,$user_id)
. I am working with role based access control.

Please help me on this.

Answer

You are using $this but you are outside object. protected static function loadRoles($dbConn,$user_id) the static function doesn execute in the object so you have 2 opportunities: 1) return the roles and do whatever you want later:

$roles = array();
while($row = $fetchRoles->fetch(PDO::FETCH_ASSOC))
{
    $roles[$row["role_name"]] = Role::getRole($dbConn,$row["role_id"]); 
}

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

}

Comments