Jursels
Jursels

Reputation: 173

Check if variable is set in function call

I have a little issue:

<?=$this->bs_forms->text_input('last_name','Name', $user->last_name);?>

If the last variable $user, does not exist I currently get some PHP errors. My solution was this:

<?=$this->bs_forms->text_input('last_name','Last Name', (isset($user))? $user->last_name : NULL);?>

But that's seems a bit hacky. Is there a better way to do this?

Upvotes: 0

Views: 82

Answers (4)

Sergey  Bulavkin
Sergey Bulavkin

Reputation: 2405

(isset($user))? $user->last_name : NULL)

Here the error is possible - "Trying to get property of non-object"

Best way:

(isset($user->last_name))? $user->last_name : NULL)

PS. Use @ - bad practice

Upvotes: 0

Will Palmer
Will Palmer

Reputation: 5952

There are other ways of doing it, but they aren't any "better" than each-other. PHP is giving you an error message, and your proposed solution isn't actually fixing the problem, it's just adding a bit of code to avoid triggering it.

The actual error that PHP is trying to tell you about is that you have gotten yourself into a situation where you are trying to execute a line of code without knowing the state of those things you are passing into it. In short: PHP is complaining that $user is undefined, because you actually have not defined any value for $user.

There are several solutions here, of equal validity (and all essentially are different ways of doing the same basic thing):

  • Ensure that this bit of code does not get called unless $user is defined. I expect you actually have several similar lines, so you may want to divide all of these up into two larger "if $user is defined" and "if $user is not defined" sections.
  • Load up an array of "default values" to pass in, and don't override those default values unless $user is defined
  • Ensure that $user is always defined, but load it with default values if the real $user doesn't exist.

Upvotes: 0

dev.meghraj
dev.meghraj

Reputation: 9120

//Ultimate    
         (isset($user))? $user->last_name : NULL)
//Best

Upvotes: 1

Barmar
Barmar

Reputation: 781721

You can use PHP's error-suppression modifier:

<?=$this->bs_forms->text_input('last_name','Name', @$user->last_name);?>

Upvotes: 0

Related Questions