开发者

in_array - 'in_object' equivalent?

Is there such a function like in_array, but can b开发者_如何学Pythone used on objects?


Nope, but you can cast the object to an array and pass it into 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.


First of all, arrays and objects are quite different.

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.

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

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 this and take a look at the examples at php.net.

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

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

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


You could cast the object to an array:

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


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


It's unbelievable how 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!

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.

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!


I don't recommend it, because it's very bad practice but you can use 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)))


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";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜