PHP의 미리 정의된 6가지 인터페이스 소개

墨辰丷
풀어 주다: 2023-03-31 12:20:02
원래의
1644명이 탐색했습니다.

이 글에서는 주로 Traversable, Iterator, IteratorAggregate, ArrayAccess, Serialized, Closure에 대한 PHP의 사전 정의된 인터페이스 소개를 소개합니다.

PHP의 사전 정의된 6가지 인터페이스 소개는 다음과 같습니다.

1.Traversable 인터페이스

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

if($class instanceof Traversable) {
  //foreach
}
로그인 후 복사

2.Iterator 반복자 인터페이스

인터페이스 요약:

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 ) //复位一个偏移位置的值
}
로그인 후 복사

다음과 같이 배열 액세스와 같은 객체에 액세스할 수 있습니다.

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 );
로그인 후 복사

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

인터페이스 요약:

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

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

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);
로그인 후 복사

6.Closure
인터페이스 요약:

Closure {
  /* 方法 */
  __construct ( void ) //用于禁止实例化的构造函数
  public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] ) //复制一个闭包,绑定指定的$this对象和类作用域。
  public Closure bindTo ( object $newthis [, mixed $newscope = 'static' ] ) //复制当前闭包对象,绑定指定的$this对象和类作用域。
}
로그인 후 복사
class A {
  private static $sfoo = 1 ;
  private $ifoo = 2 ;
}
 $cl1 = static function() {
  return A :: $sfoo ;
};
 $cl2 = function() {
  return $this -> ifoo ;
};
 
 $bcl1 = Closure :: bind ( $cl1 , null , 'A' );
 $bcl2 = Closure :: bind ( $cl2 , new A (), 'A' );
echo $bcl1 (), "\n" ;
echo $bcl2 (), "\n" ;
로그인 후 복사

Summary: 위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다.

관련 권장 사항:

PHP 변수의 결정 및 동적 정의

PHP 배열을 Apple plist XML 또는 텍스트 형식으로 변환하는 기능

php는 중국 프록시 서버 네트워크의 집합을 실현합니다

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

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!