PHP内置接口类
阅读 915 作者 阿林

 

JsonSerializable接口
 
// 内置
JsonSerializable {
    // 方法
    abstract public jsonSerialize ( void ) : mixed
}

// 实现
class JsonTest implements JsonSerializable {
    private $a, $b;
 
    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }
 
    public function jsonSerialize() {
        return [$this->a, $this->b];
    }
}
 
echo json_encode(new JsonTest(3, 4));
//[3,4]
 
IteratorAggregate接口
聚合式迭代器,它提供了创建外部迭代器的接口
// 内置
IteratorAggregate extends Traversable {
    abstract public Traversable getIterator ( void )
}

class myData implements IteratorAggregate {
    private $one = "one";
    protected $two = "two";
    public $three = "three";
 
    public function __construct() {
        $this->last = "last";
    }
 
    public function getIterator() {
        return new ArrayIterator($this);
    }
}
 
$obj = new myData;
print_r($obj);

myData Object
(
    [one:myData:private] => one
    [two:protected] => two
    [three] => three
    [last] => last
)
ArrayAccess接口
ArrayAccess {
    // Methods 
    abstract public offsetExists ( mixed $offset ) : bool
    abstract public offsetGet ( mixed $offset ) : mixed
    abstract public offsetSet ( mixed $offset , mixed $value ) : void
    abstract public offsetUnset ( mixed $offset ) : void
}