我正在编写一个包含其他对象集合的类。我将创建一个方法将集合中的元素从一个位置移动到另一个位置,另一个用于确定已更改的内容等。
不是从头开始,是否有一些我应该扩展的预建类?我希望我应该使用spl,但我对PHP的这一部分很新,并且不确定从哪里开始。我最近遇到class.arrayobject,但似乎没有扩展的内容。
class Collection
{
protected $stack=[];
private $originalStack;
public function __construct(array $nodes=[]) { //$nodes is an array of Node objects
$this->stack=$nodes;
$this->originalStack=array_merge(array(), $nodes); //Arrays not passed by reference but the objects are!
}
public function getChanges(){
$this->stack;
}
public function getPositionChanges($prop){
return array_udiff_assoc($this->stack, $this->originalStack,
function ($stack, $originalStack) {
return is_numeric($stack->$prop) && is_numeric($originalStack->$prop)
?$stack->$prop - $originalStack->$prop
:strcmp($stack->$prop, $originalStack->$prop);
}
);
}
public function getAll(){
$this->stack;
}
public function getByPosition(int $position){
$this->stack[$position];
}
public function getPropertyByPosition(int $position, $property){
return $this->stack[$position]->$property; //Uses __get
}
public function add(Node $elem){
$this->stack[]=$elem;
}
public function delete(int $position){
if(!isset($this->stack[$position])) throw new CollectionException('Index does not exist');
unset($this->stack[$position]);
$this->stack=$stack[]=array_values($this->stack);
}
public function move(int $initialPosition, int $finalPosition){
if(!isset($this->stack[$initialPosition]) || !isset($this->stack[$finalPosition])) throw new CollectionException('Index does not exist');
$node=$this->stack[$initialPosition];
unset($this->stack[$initialPosition]);
array_splice($this->stack, $finalPosition, 0, $node);
$this->stack=array_values($this->stack);
//?? return $this->stack;
}
public function update(int $position, $property, $value){
if(!isset($this->stack[$position])) throw new CollectionException('Index does not exist');
$this->stack[$position]->$property=$value; //Uses __set
}
}