php in_array - 'in_object' 等价物?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5041533/
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 16:37:01  来源:igfitidea点击:

in_array - 'in_object' equivalent?

phpfunction

提问by davivid

Is there such a function like in_array, but can be used on objects?

有没有像in_array, 但可以用在对象上的函数?

回答by BoltClock

Nope, but you can cast the object to an array and pass it into in_array().

不,但您可以将对象转换为数组并将其传递到in_array().

$obj = new stdClass;
$obj->one = 1;
var_dump(in_array(1, (array) $obj)); // bool(true)

That violates all kinds of OOP principles though. See my comment on your question and Aron's answer.

但这违反了各种 OOP 原则。请参阅我对您的问题的评论和Aron 的回答

回答by Aron Rotteveel

First of all, arraysand objectsare quitedifferent.

首先,数组对象完全不同的。

A PHP object can not be iterated through like an array, by default. A way to implement object iteration is to implement the Iterator interface.

默认情况下,PHP 对象不能像数组一样迭代。实现对象迭代的一种方法是实现 Iterator 接口。

Concerning your specific question, you probably want to take a look at the ArrayAccess interface:

关于您的具体问题,您可能想看看ArrayAccess 接口

class obj implements ArrayAccess {
    private $container = array();
    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }
    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }
    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }
    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }
    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

Now you can access your object like an array in the following manner:

现在,您可以通过以下方式像数组一样访问您的对象:

$object = new obj();
var_dump(isset($obj['two'])); // exists!
var_dump(isset($obj['foo'])); // does not exist

Before you go crazy on this though, please consider why you are actually trying to do thisand take a look at the examples at php.net.

不过,在您为此发疯之前,请考虑您实际尝试这样做的原因,并查看 php.net 上的示例。

Option 2: when you are simply trying to see if a property exists, you can use property_exists()for this:

选项 2:当您只是想查看属性是否存在时,您可以使用property_exists()来实现:

class foo {
    public $bar = 'baz';
}

$object = new foo();
var_dump(property_exists($object, 'bar')); // true

回答by powtac

function in_object($needle, $haystack) {
    return in_array($needle, get_object_vars($haystack));
}

回答by Floern

You could cast the object to an array:

您可以将对象强制转换为数组:

$obj = new stdClass();
$obj->var = 'foobar';
in_array( 'foobar', (array)$obj ); // true

回答by xzyfer

I don't recommend it, because it's very bad practice but you can use get_object_vars.

我不推荐它,因为这是非常糟糕的做法,但您可以使用get_object_vars

Gets the accessible non-static properties of the given object according to scope.

根据范围获取给定对象的可访问非静态属性。

There are other limitations you should refer to the documentation to see if it is suitable for you.

还有其他限制,您应该参考文档以查看它是否适合您。

if(in_array('find me', get_object_vars($obj)))

回答by Chris Michaelides

It's unbelievablehow all the people miss the point of the usefulness of an in_object PHP method! Here is what I came up with, it is very useful, and you will see why!

令人难以置信的是,所有人都忽略了 in_object PHP 方法的有用性!这是我想出的,它非常有用,你会明白为什么!

Here is a simple function I wrote which will check if a value can be found within an object.

这是我编写的一个简单函数,它将检查是否可以在对象中找到一个值。

<?php
  // in_object method
  // to check if a value in an object exists.
  function in_object($value,$object) {
    if (is_object($object)) {
      foreach($object as $key => $item) {
        if ($value==$item) return $key;
      }
    }
    return false;
  }
?>

This is very useful if an object has been created dynamically(especially from external code, which you don't control, as in an application-plugin, CMS, etc), and you don't know the object's properties. The above function will return the property, so you will be able to use it in your code later on.

如果对象是动态创建的(尤其是从外部代码创建的,您无法控制,例如在应用程序插件、CMS 等中),并且您不知道对象的属性,这将非常有用。上面的函数将返回该属性,因此您稍后可以在代码中使用它。

Here is a very good basic example of how useful this function is!

这是一个很好的基本示例,说明了此功能的有用性!

<?php
  class My_Class {
    function __construct($key, $value) {
      $this->$key = $value;
      // As you can see, this is a dynamic class, its properties and values can be unknown...
    }
  }

  function in_object($value,$object) {
    if (is_object($object)) {
      foreach($object as $key => $item) {
        if ($value==$item) return $key;
      }
    }
    return false;
  }

  function manipulate_property($value,$object) {
    if ($property = in_object($value,$object)) {
      // value found. I can now use this property.
      // I can simply echo'it (makes no sense, as I could instead simply echo "value")
      echo "<br />I found the property holding this value: ".$object->$property;
      // or (here comes the good part)
      // change the property
      $object->$property = "This is a changed value!";
      echo "<br />I changed the value to: ".$object->$property;
      // or return it for use in my program flow
      return $property;
    } else {
      echo "Value NOT FOUND!<br />";
      return false;
    }
  }

  // imagine if some function creates the class conditionally...
  if ( 1 == 1) {
    $class = new My_Class("property","Unchanged Value");
  } else {
    $class = new My_Class("property","Some Other Value");
  }

  // now let's check if the value we want exists, and if yes, let's have some fun with it...
  $property = manipulate_property("Unchanged Value",$class);
  if ($property) {
    $my_variable = $class->$property;
    echo "<br />This is my variable now:".$my_variable;
  } else $my_variable = $some_other_variable;
?>

Just run it to see for yourself!

只需运行它自己看看!

回答by iamnamrud

This is the most efficient and correct solution. With some modifications it could be applied to check any data type present in any object.

这是最有效和最正确的解决方案。通过一些修改,它可以应用于检查任何对象中存在的任何数据类型。

if(gettype($object->var1->var2) == "string"){
echo "Present";
}