假如在未做任何处置惩罚的情况下, 以数组的体式格局接见对象,会抛给你一个大大的毛病。
Fatal error: Uncaught Error: Cannot use object of type Test as array
固然假如你对类举行一些革新的话,照样能够像数组一样接见。
怎样接见受庇护的对象属性
在正式革新之前,先看另一个题目。当我们试图接见一个受庇护的属性的时刻,也会抛出一个大大的毛病。
Fatal error: Uncaught Error: Cannot access private property Test::$container
是否是受庇护属性就不能猎取?固然不是,假如我们想要猎取受庇护的属性,我们能够借助把戏要领__get。
相干引荐:《php数组》
DEMO1
猎取私有属性
<?php class Test { private $container = []; public function __construct() { $this->container = ['one'=>1, 'two'=>2, 'three'=>3]; } public function __get($name) { return property_exists($this, $name) ? $this->$name : null; } } $test = new Test(); var_dump($test->container);
DEMO2
猎取私有属性下对应键名的键值。
<?php class Test { private $container = []; public function __construct() { $this->container = ['one'=>1, 'two'=>2, 'three'=>3]; } public function __get($name) { return array_key_exists($name, $this->container) ? $this->container[$name] : null; } } $test = new Test(); var_dump($test->one);
怎样以数组的体式格局接见对象
我们须要借助预定义接口中的ArrayAccess接口来完成。接口中有4个笼统要领,须要我们完成。
<?php class Test implements ArrayAccess { private $container = []; public function __construct() { $this->container = ['one'=>1, 'two'=>2, 'three'=>3]; } public function offsetExists($offset) { return isset($this->container[$offset]); } public function offsetGet($offset){ return isset($this->container[$offset]) ? $this->container[$offset] : null; } public function offsetSet($offset, $value) { if(is_null($offset)){ $this->container[] = $value; }else{ $this->container[$offset] = $value; } } public function offsetUnset($offset){ unset($this->container[$offset]); } } $test = new Test(); var_dump($test['one']);
怎样遍历对象
实在对象在不做任何处置惩罚的情况下,也能够被遍历,然则只能遍历可见属性,也就是定义为public的属性。我们能够借助另一个预定义接口IteratorAggregate,来完成更加可控的对象遍历。
<?php class Test implements IteratorAggregate { private $container = []; public function __construct() { $this->container = ['one'=>1, 'two'=>2, 'three'=>3]; } public function getIterator() { return new ArrayIterator($this->container); } } $test = new Test(); foreach ($test as $k => $v) { var_dump($k, $v); }
以上就是php数组中对象怎样接见的细致内容,更多请关注ki4网别的相干文章!