PHP中预定义的6种接口介绍
|
PHP预定义了6个接口介绍如下: 1.Traversable遍历接口 呵呵!其实它不是一个在PHP中可以使用的接口,内部类才可使用,它有一个用途就是检测一个类是否可以遍历。 2.Iterator迭代器接口 接口摘要: 以上可以让一个类实现一个基本的迭代功能,如下可以看到迭代的调用顺序: public function __construct () {$this -> position = 0 ; } function rewind () { function current () { function key () { function next () { function valid () { $it = new myIterator ; foreach( $it as $key => $value ) { 3.IteratorAggregate聚合式迭代器接口 接口摘要: //获取外部迭代器abstract public Traversable getIterator ( void ) } getIterator是一个Iterator或Traversable接口的类的一个实例。如下获取外部迭代器实现迭代访问。 public function __construct () {$this -> property4 = "last property" ; } public function getIterator () { $obj = new myData ; foreach( $obj as $key => $value ) { 4.ArrayAccess数组式访问接口 接口摘要: 如下可像访问数组一样访问对象: 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 ; } }$obj = new obj ; var_dump (isset( $obj [ "two" ])); 5.Serializable序列化接口接口摘要: / 方法 /abstract public string serialize ( void ) //对象的字符串表示 abstract public mixed unserialize ( string $serialized ) // 构造对象 } 实现该接口的类不再支持__sleep()和__wakeup()。使用很简单,只要序列化对象时serialize方法会被调用,当反序列化时,unserialize方法被调用。 data = "My private data" ; } public function serialize () { return serialize ( $this -> data ); } public function unserialize ( $data ) { $this -> data = unserialize ( $data ); } public function getData () { return $this -> data ; } }$obj = new obj ;
6.Closure 接口摘要: ifoo ; };$bcl1 = Closure :: bind ( $cl1,null,'A' ); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
