1

Is there a way to set object parameter value to empty string or null if object does not exist instead of fatal error?

Lets say i have this in my view:

<div> <?php $car->name; ?> </div

And there is a chance that car is empty object in some cases. I just could write my own function that checks object and return object parameter or empty string, but i want to know if there is a default way to do this.

Another way would be use shorthand if statement, as in

($car) ? $car->name : "";

but it is too long to but in view IMHO.

1
  • If your object is a method and not stdClass, you can use __call method Commented Oct 28, 2016 at 12:56

1 Answer 1

1

You have a few different options

The long way is using one of the following functions in an if statement:

  • isset
  • empty

example

if(!isset($car->name)) {
    return 'No car';
} 

using empty

if(empty($car->name)) {
    return 'No car';
} 

Or you can combine both if you really wanted.

You can also use them in shorthand as you have done above or using the isset and or empty functions.

If you are using PHP version 7 you can use a new feature that shipped with it called Null coalescing operator (??)

Example:

echo $car->name ?? 'No car';

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

I am running PHP7 and use it daily!

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.