views:

305

answers:

3

I am getting this error in a PHP class...

Fatal error: Can't use method return value in write context in C:\webserver\htdocs\friendproject2\includes\classes\User.class.php on line 35

Here is the troubled part.

if(isset($this->session->get('user_id')) && $this->session->get('user_id') != ''){
    //run code
}

This code is in my contrustor, is a value is not already set for $this->session->get('user_id') then it will return false instead of a Number. So as you can see I was hoping to check if this value is a number or not or not even set.

Any help with fixing appreciated.

+6  A: 

You can't use isset for the result of a function. Consider the following code instead:

if( $this->session->get('user_id') ){
    //run code
}
St.Woland
Hah! Learnt something. +1
Pekka
Remember that if your application allows for a user_id with the value 0, this will fail, as 0 evaluates to false. A user_id of 0 might be unlikely in many applications, but still wanted to point it out.
fireeyedboy
Hmmm, now that I read the OP's question more thoroughly, I see he mentioned the method returns false if there is no user_id. Still, maybe: if( false !== $this->session->get('user_id') ) ... might be a little more save.
fireeyedboy
+10  A: 

isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.

From the PHP Manual.

Alix Axel
+1  A: 

You can't use isset on a function. However, since false, 0, and '' all equate to a falsey statement, write your test this way:

if( $id = $this->sessions->get('user_id') ){
   // Will only run if $id does not equal '', False, or 0
}

That way you have run your test and assigned the variable in one step.

Doug Neiner
Frank Farmer