我知道PHP没有一个纯对象变量,但我想检查属性是否在给定的对象或类中。

$ob = (object) array('a' => 1, 'b' => 12); 

or

$ob = new stdClass;
$ob->a = 1;
$ob->b = 2;

在JS中,我可以写这个来检查变量a是否存在于一个对象中:

if ('a' in ob)

在PHP中,可以做到这一点吗?


当前回答

isset和property_exists都不适合我。

如果属性存在但为NULL, isset返回false。 如果属性是对象类定义的一部分,Property_exists返回true,即使它没有被设置。

最后我的答案是:

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

例子:

    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
        }
    }

其他回答

如果您想知道某个属性是否存在于已定义的类的实例中,只需将property_exists()与isset()结合起来即可。

public function hasProperty($property)
{
    return property_exists($this, $property) && isset($this->$property);
}

要检查属性是否存在,以及是否也为空,可以使用函数property_exists()。

文档:http://php.net/manual/en/function.property-exists.php

与isset()相反,即使属性值为NULL, property_exists()也会返回TRUE。

Bool类型:property_exists(混合$class,字符串$property)

例子:

if (property_exists($testObject, $property)) {
    //do something
}

这是非常新的,所以请确保您运行的是PHP 8:

$ob?->a

参考链接

Property_exists(混合$class,字符串$property)

if (property_exists($ob, 'a')) 

Isset (mixed $var [, mixed $…])

注意:注意,如果属性为空,isset()将返回false

if (isset($ob->a))

示例1:

$ob->a = null
var_dump(isset($ob->a)); // false

示例2:

class Foo
{
   public $bar = null;
}

$foo = new Foo();

var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false

通常我使用自定义助手

    /**
     * @param Object $object
     * @param string $property as a string with nested properties 'prop1.nesterdProp.deepvalue'
     * @param mixed $default
     * @return mixed
     */
    function getPropertyOrDefault(Object $object, string $property, $default = null)
    {
        $value = $object;
        $path = explode('.', $property);
        foreach ($path as $prop) {
            if (is_object($value) && property_exists($value, $prop)) {
                $value = $value->{$prop};
            } else {
                return $default;
            }
        }
        return $value;
    }

请记住,如果属性为空,您将得到空值,没有默认值。

顺便说一下,类似的helper在JS中也可以工作。