脚本宝典收集整理的这篇文章主要介绍了php – 重新组织SplObjectStorage实例的子项,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
例:
<?PHP $Store = new SplObjectStorageWrapPEr; $obj1 = new Obj; $obj2 = new Obj; $obj3 = new Obj; $store->attach($obj1); $store->attach($obj2); $store->insertAtIndex($obj3,1); //Storage should Now be organized as $obj1,$obj3,$obj2
我将如何实现insertAtIndex方法?我是否使用LimITIterator在某个位置后分离并重新连接孩子?事实证明,使用基于数组的对象存储比SplObjectStorage实例要慢得多.
<?PHP /** * Extends the SplObjectStorage class to PRovide index functions */ class ObjectStorage extends SplObjectStorage { /** * Returns the index of a given object,or false if not found * @param object $object */ function indexOf($object){ if(!$this->contains($object)) return false; foreach($this as $index => $obj) if($obj === $object) return $index; } /** * Returns the object at the given index */ function itemAtIndex($index){ $it = new LimitIterator($this,$index,1); foreach($it as $obj) return $obj; } /** * Returns the sequence of objects as specified by the offset and length * @param int $offset * @param int $length */ function slice($offset,$length){ $out = array(); $it = new LimitIterator($this,$offset,$length); foreach($it as $obj) $out[] = $obj; return $out; } /** * Inserts an object (or an array of objects) at a certain point * @param mixed $object A single object or an array of objects * @param integer $index */ function insertAt($object,$index){ if(!is_array($object)) $object = array($object); //Check to ensure that objects don't already exist in the collection foreach($object as $k => $obj): if($this->contains($obj)) unset($object[$k]); enDForeach; //Do we have any objects left? if(!$object) return; //Detach any objects at or past this index $remaining = array(); if($index < $this->count()): $remaining = $this->slice($index,$this->count() - $index); foreach($remaining as $obj) $this->detach($obj); endif; //Add the new objects we're splicing in foreach($object as $obj) $this->attach($obj); //Attach the objects we prevIoUsly detached foreach($remaining as $obj) $this->attach($obj); } /** * Removes the object at the given index * @param integer $index */ function removeAt($index){ $this->detach($this->itemAtIndex($index)); } }
以上是脚本宝典为你收集整理的php – 重新组织SplObjectStorage实例的子项全部内容,希望文章能够帮你解决php – 重新组织SplObjectStorage实例的子项所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。