Reputation: 173
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
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
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):
$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.$user
is defined$user
is always defined, but load it with default values if the real $user
doesn't exist.Upvotes: 0
Reputation: 781721
You can use PHP's error-suppression modifier:
<?=$this->bs_forms->text_input('last_name','Name', @$user->last_name);?>
Upvotes: 0