>  기사  >  백엔드 개발  >  PHP에서 사전 정의된 6가지 인터페이스 분석

PHP에서 사전 정의된 6가지 인터페이스 분석

*文
*文원래의
2017-12-28 09:43:291285검색

이 글에서는 PHP에서 미리 정의된 6가지 인터페이스를 주로 소개하고 Traversable, Iterator, IteratorAggregate, ArrayAccess, Serialized, Closure에 대해 자세히 설명합니다. 그것이 모두에게 도움이 되기를 바랍니다.

PHP 사전 정의된 6개의 인터페이스는 다음과 같이 소개됩니다:

1.Traversable traversal 인터페이스

하하! 실제로 이는 PHP에서 사용할 수 있는 인터페이스가 아니며 내부 클래스만 사용할 수 있습니다. 그 용도 중 하나는 클래스를 탐색할 수 있는지 여부를 감지하는 것입니다.


if($class instanceof Traversable) {
  //foreach
}


2. 반복자 인터페이스

인터페이스 요약:


Iterator extends Traversable 
{ 
  //返回当前索引游标指向的元素 
  abstract public mixed current(void) 
  //返回当前索引游标指向的元素的键名 
  abstract public scalar key(void) 
  //移动当前索引游标指向下一元素 
  abstract public void next(void) 
  //重置索引游标的指向第一个元素 
  abstract public void rewind(void) 
  //判断当前索引游标指向的是否是一个元素,常常在调用 rewind()或 next()使用 
  abstract public boolean valid(void) 
}


위를 통해 클래스는 다음과 같이 반복 호출 순서를 볼 수 있습니다.


class myIterator implements Iterator {
  private $position = 0 ;
  private $array = array(
    "firstelement" ,
    "secondelement" ,
    "lastelement" ,
  );
 
  public function __construct () {
    $this -> position = 0 ;
  }
 
  function rewind () {
    var_dump ( __METHOD__ );
    $this -> position = 0 ;
  }
 
  function current () {
    var_dump ( __METHOD__ );
    return $this -> array [ $this -> position ];
  }
 
  function key () {
    var_dump ( __METHOD__ );
    return $this -> position ;
  }
 
  function next () {
    var_dump ( __METHOD__ );
    ++ $this -> position ;
  }
 
  function valid () {
    var_dump ( __METHOD__ );
    return isset( $this -> array [ $this -> position ]);
  }
}
 
$it = new myIterator ;
 
foreach( $it as $key => $value ) {
  var_dump ( $key , $value );
  echo "\n" ;
}


3. IteratorAggregate 집계 반복자 인터페이스

인터페이스 요약:


IteratorAggregate extends Traversable {
 
//获取外部迭代器
abstract public Traversable getIterator ( void )
}


getIterator는 Iterator 또는 Traversable 인터페이스 클래스의 인스턴스입니다. 반복 액세스를 구현하려면 다음과 같이 외부 반복자를 얻습니다.


class myData implements IteratorAggregate {
  public $property1 = "Public property one" ;
  public $property2 = "Public property two" ;
  public $property3 = "Public property three" ;
 
  public function __construct () {
    $this -> property4 = "last property" ;
  }
 
  
  public function getIterator () {
    return new ArrayIterator ( $this );
  }
}
 
$obj = new myData ;
 
foreach( $obj as $key => $value ) {
  var_dump ( $key , $value );
  echo "\n" ;
}


4. ArrayAccess 배열 액세스 인터페이스

인터페이스 요약:


ArrayAccess {
  /* 方法 */
  abstract public boolean offsetExists ( mixed $offset ) //检查偏移位置是否存在
  abstract public mixed offsetGet ( mixed $offset ) //获取一个偏移位置的值
  abstract public void offsetSet ( mixed $offset , mixed $value ) //设置一个偏移位置的值
  abstract public void offsetUnset ( mixed $offset ) //复位一个偏移位置的值
}


객체는 다음과 같이 배열처럼 액세스할 수 있습니다.


rrre 에에


5 .직렬화 가능한 직렬화 인터페이스

인터페이스 요약:


class obj implements arrayaccess {
  private $container = array();
  public function __construct () {
    $this -> 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" ]));
var_dump ( $obj [ "two" ]);
unset( $obj [ "two" ]);
var_dump (isset( $obj [ "two" ]));
$obj [ "two" ] = "A value" ;
var_dump ( $obj [ "two" ]);
$obj [] = 'Append 1' ;
$obj [] = 'Append 2' ;
$obj [] = 'Append 3' ;
print_r ( $obj );


이 인터페이스를 구현하는 클래스는 더 이상 __sleep() 및 __wakeup()을 지원하지 않습니다. 객체가 직렬화될 때 serialize 메서드가 호출되고, 역직렬화될 때 unserialize 메서드가 호출되는 한 사용은 매우 간단합니다.


Serializable {
 
  /* 方法 */
  abstract public string serialize ( void ) //对象的字符串表示
  abstract public mixed unserialize ( string $serialized ) // 构造对象
}



6. Closure

인터페이스 요약:


class obj implements Serializable {
  private $data ;
  public function __construct () {
    $this -> 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 ;
$ser = serialize ( $obj );
print_r($ser);
$newobj = unserialize ( $ser );
print_r($newobj);



Closure {
  /* 方法 */
  __construct ( void ) //用于禁止实例化的构造函数
  public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] ) //复制一个闭包,绑定指定的$this对象和类作用域。
  public Closure bindTo ( object $newthis [, mixed $newscope = 'static' ] ) //复制当前闭包对象,绑定指定的$this对象和类作用域。
}

관련 권장 사항:

PHP 인터페이스 클래스와 추상의 실제 역할 수업

PHP 보안 토크 php 인터페이스 보안 php 보안 감지 php.ini 보안 구성

PHP 인터페이스 및 참조 인터페이스 자세한 설명_PHP 튜토리얼


위 내용은 PHP에서 사전 정의된 6가지 인터페이스 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.