1

I have the following code where I try to assign a value to a variable and then evaluate if it's empty:

if(!empty($user = User::find($id))){
   // do some operations on the $user
}

But I'm getting an error... Does the PHP compiler allows this in any way?

PS. I'm using PHP 5.3

3
  • If you have $user previously in the context then put == instead of = otherwise the return value of User::find is not suitable for empty. Commented Dec 22, 2012 at 16:32
  • 2
    @MahanGM I believe he's assigning a value rather than comparing it Commented Dec 22, 2012 at 16:33
  • php is an interpreted language. what php compiler are you using, hiphop? can you provide some additional context? also, I think you should reconsider checking for !empty on the find method you are calling with an injected value. If you were unit testing this it would be a mess. break out your functionality into reuseable units. Commented Dec 22, 2012 at 16:39

2 Answers 2

3

Does the PHP compiler allows this in any way?

Check out manual page about empty:

Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error.

In your code you have assignment operation instead of plain variable.

Sign up to request clarification or add additional context in comments.

Comments

1

Generally if a function cant find something, ie a User, then it would return false anyway - so this is what I normally do:

if($user = User::find($id))
   // do some operations on the $user
}
else
{
   // no user found 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.