in_array - 'in_object'等价?

dav*_*vid 22 php function

有这样的功能in_array,但可以用在对象上吗?

Bol*_*ock 25

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

$obj = new stdClass;
$obj->one = 1;
var_dump(in_array(1, (array) $obj)); // bool(true)
Run Code Online (Sandbox Code Playgroud)

这违反了各种OOP原则.看看我对你的问题的评论和Aron的回答.


Aro*_*eel 15

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

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

关于您的具体问题,您可能想看一下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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以按以下方式访问对象,如数组:

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

在你疯狂之前,请考虑为什么你真的想要这样做并看看php.net上的例子.

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

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

$object = new foo();
var_dump(property_exists($object, 'bar')); // true
Run Code Online (Sandbox Code Playgroud)


pow*_*tac 7

function in_object($needle, $haystack) {
    return in_array($needle, get_object_vars($haystack));
}
Run Code Online (Sandbox Code Playgroud)


Flo*_*ern 6

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

$obj = new stdClass();
$obj->var = 'foobar';
in_array( 'foobar', (array)$obj ); // true
Run Code Online (Sandbox Code Playgroud)