PHP check whether property exists in object or class

后端 未结 8 1514
情深已故
情深已故 2020-12-02 11:01

I understand PHP does not have a pure object variable, but I want to check whether a property is in the given object or class.

$ob = (object) array(\'a\' =&g         


        
相关标签:
8条回答
  • 2020-12-02 11:29

    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';

    0 讨论(0)
  • 2020-12-02 11:34

    Neither isset or property_exists work for me.

    • isset returns false if the property exists but is NULL.
    • property_exists returns true if the property is part of the object's class definition, even if it has been unset.

    I ended up going with:

        $exists = array_key_exists($property, get_object_vars($obj));
    

    Example:

        class Foo {
            public $bar;
    
            function __construct() {
                $property = 'bar';
    
                isset($this->$property); // FALSE
                property_exists($this, $property); // TRUE
                array_key_exists($property, get_object_vars($this)); // TRUE
    
                unset($this->$property);
    
                isset($this->$property); // FALSE
                property_exists($this, $property); // TRUE
                array_key_exists($property, get_object_vars($this)); // FALSE
    
                $this->$property = 'baz';
    
                isset($this->$property); // TRUE
                property_exists($this, $property); // TRUE
                array_key_exists($property, get_object_vars($this));  // TRUE
            }
        }
    
    0 讨论(0)
提交回复
热议问题