PHP 检查属性是否存在于对象或类中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14414379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:12:49  来源:igfitidea点击:

PHP check whether property exists in object or class

phpclassvariablesobjectparameters

提问by Micah

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.

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

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

or

或者

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

In JS,I can write this to check if variable aexists in an object:

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

if ('a' in ob)

In PHP,can anything like this be done?

PHP 中,可以做这样的事情吗?

Thank you very much for your advice.

非常感谢您的建议。

回答by Peter

property_exists( mixed $class , string $property )

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

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

isset( mixed $var [, mixed $... ] )

isset( 混合 $var [, 混合 $... ] )

if (isset($ob->a))

isset() will return false if property is null

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

Example 1:

示例 1:

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

Example 2:

示例 2:

class Foo
{
   public $bar = null;
}

$foo = new Foo();

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

回答by Chiara Perino

To check if the property exists and if it's null too, you can use the function property_exists().

要检查该属性是否存在以及它是否也为 null,您可以使用函数property_exists().

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

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

As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

与 isset() 不同,即使该属性的值为 NULL,property_exists() 也会返回 TRUE。

bool property_exists ( mixed $class , string $property )

bool property_exists ( 混合 $class ,字符串 $property )

Example:

例子:

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

回答by smariot

Neither issetor property_existswork for me.

issetproperty_exists都不适合我。

  • issetreturns false if the property exists but is NULL.
  • property_existsreturns true if the property is part of the object's class definition, even if it has been unset.
  • 如果属性存在但为 NULL,则isset返回 false。
  • 如果属性是对象的类定义的一部分,则property_exists返回 true,即使它已被取消设置。

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

回答by Rob

Solution

解决方案

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

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 语句中展示它的外观。

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:

检查某些东西是否存在的传统 PHP 方法是:

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

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

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_NOTICEand is not best practise. If the value is nullit will not raise the exception.

但是......如果该值不存在(未设置),它将引发一个E_NOTICE并且不是最佳实践。如果值为null,则不会引发异常。

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

因此,三元运算符的救援使这是一个简洁的小答案:

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

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

回答by Anthony Rutledge

If you want to know if a property exists in an instanceof a class that you have defined, simply combine property_exists()with isset().

如果你想知道,如果在存在一个属性实例,您已经定义的类的,只是结合property_exists()使用isset()

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

回答by Tjoene

To check if something exits, you can use the PHP function isset() see php.net. This function will check if the variable is set and is not NULL.

要检查是否存在某些内容,您可以使用 PHP 函数 isset()参见 php.net。此函数将检查变量是否已设置且不为 NULL。

Example:

例子:

if(isset($obj->a))
{ 
  //do something
}

If you need to check if a property exists in a class, then you can use the build in function property_exists()

如果需要检查类中是否存在属性,则可以使用内置函数property_exists()

Example:

例子:

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

回答by Ali_Hr

Using array_key_exists() on objects is Deprecated in php 7.4

在对象上使用 array_key_exists() 在 php 7.4 中已弃用

Instead either isset() or property_exists() should be used

相反,应该使用 isset() 或 property_exists()

reference : php.net

参考:php.net

回答by Victor

Just putting my 2 cents here.

只是把我的 2 美分放在这里。

Given the following class:

鉴于以下类:

class Foo
{
  private $data;

  public function __construct(array $data)
  {
    $this->data = $data;
  }

  public function __get($name)
  {
    return $data[$name];
  }

  public function __isset($name)
  {
    return array_key_exists($name, $this->data);
  }
}

the following will happen:

将发生以下情况:

$foo = new Foo(['key' => 'value', 'bar' => null]);

var_dump(property_exists($foo, 'key'));  // false
var_dump(isset($foo->key));  // true
var_dump(property_exists($foo, 'bar'));  // false
var_dump(isset($foo->bar));  // true, although $data['bar'] == null

Hope this will help anyone

希望这会帮助任何人