Check property exists in object php

Solution

echo $person->middleName ?? 'Person does not have a middle name';

To show how this would look in an if statement for more clarity on how this is working.

if[$person->middleName ?? false] {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

Explanation

The traditional PHP way to check for something's existence is to do:

if[isset[$person->middleName]] {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

OR for a more class specific way:

if[property_exists[$person, 'middleName']] {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

These are both fine in long form statements but in ternary statements they become unnecessarily cumbersome like so:

isset[$person->middleName] ? echo $person->middleName : echo 'Person does not have a middle name';

You can also achieve this with just the ternary operator like so:

echo $person->middleName ?: 'Person does not have a middle name';

But... if the value does not exist [is not set] it will raise an E_NOTICE and is not best practise. If the value is null it will not raise the exception.

Therefore ternary operator to the rescue making this a neat little answer:

echo $person->middleName ?? 'Person does not have a middle name';

[PHP 5 >= 5.1.0, PHP 7, PHP 8]

property_exists Checks if the object or class has a property

Description

property_exists[object|string $object_or_class, string $property]: bool

Note:

As opposed with isset[], property_exists[] returns true even if the property has the value null.

Parameters

object_or_class

The class name or an object of the class to test for

property

The name of the property

Return Values

Returns true if the property exists, false if it doesn't exist or null in case of an error.

Examples

Example #1 A property_exists[] example

Notes

Note:

Using this function will use any registered autoloaders if the class is not already known.

Note:

The property_exists[] function cannot detect properties that are magically accessible using the __get magic method.

g dot gentile at parentesigraffe dot com

7 years ago

The function behaves differently depending on whether the property has been present in the class declaration, or has been added dynamically, if the variable has been unset[]

Nanhe Kumar

8 years ago

falundir at gmail dot com

5 years ago

If you want to test if declared *public* property was unset, you can use the following code:

@fitorec

3 years ago

Daniel dot Peder at infoset dot com

5 years ago

declared properties cannot be unset
any set property does exist, even being set to null, regardless how it was set

Chủ Đề