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

PHP 사전 정의된 인터페이스 분석

不言
不言원래의
2018-06-15 11:19:061480검색

이 글에서는 주로 PHP의 사전 정의된 인터페이스를 정리했습니다. 일상적인 프로젝트 프로세스에서 일반적으로 사용되는 네 가지 인터페이스는 IteratorAggregate(집계 집계 반복자 Iterator), Countable, ArrayAccess, Iterator입니다.

사전 정의된 인터페이스가 여러 개 있습니다. PHP에서 일반적으로 사용되는 4가지 인터페이스(IteratorAggregate(aggregate iterator Iterator), Countable, ArrayAccess, Iterator)를 각각 자세히 소개합니다.

IteratorAggregate(집계 반복자 Iterator) 인터페이스

IteratorAggregate extends Traversable {
 abstract public Traversable getIterator(void)
}

이 인터페이스는 외부 반복자를 생성하는 함수를 구현합니다. foreach를 사용하여 객체를 탐색할 때 의 상속이 없는 경우 IteratorAggregate 인터페이스와 객체의 모든 공개 속성이 탐색됩니다(공용 $var 형식으로만). IteratorAggregate를 상속하는 경우 클래스에 구현된 getIterator 메서드에서 반환된 개체가 사용됩니다. 여기서 반환된 개체는 Traversable 개체 또는 Traversable에서 확장된 개체여야 합니다. 그렇지 않으면 예외가 발생합니다.

//看个例子
class My{
 private $_data = [
 'a' => '燕睿涛',
 'b' => 'yanruitao',
 'c' => 'LULU',
 ];
 
 public function getIterator()
 {
 return new ArrayIterator($this->_data);
 }
}
$obj = new My;
foreach ($obj as $key => $value) {
 echo "$key => $value\n";
}
//输出结果为空 

class My implements IteratorAggregate {
 private $_data = [
 'a' => '燕睿涛',
 'b' => 'yanruitao',
 'c' => 'LULU',
 ];

 public function getIterator()
 {
 return new ArrayIterator($this->_data);
 }
}
$obj = new My;
foreach ($obj as $key => $value) {
 echo "$key => $value\n";
}
//结果:
a => 燕睿涛
b => yanruitao
c => LULU

Countable 인터페이스

Countable {
 abstract public int count(void)
}

이 인터페이스는 객체의 수를 세는 데 사용됩니다. 구체적으로 어떻게 이해해야 할까요? 객체에 대해 count를 호출할 때 함수가 Countable을 상속하지 않으면 항상 1을 반환합니다. Countable 을 상속하면 구현된 count 메서드에서 반환된 숫자를 반환합니다. 다음 예를 살펴보세요.

class CountMe
{ 
 protected $_myCount = 3; 

 public function count() 
 { 
 return $this->_myCount; 
 } 
} 

$countable = new CountMe(); 
echo count($countable);
//返回1

class CountMe implements Countable
{ 
 protected $_myCount = 3; 

 public function count() 
 { 
 return $this->_myCount; 
 } 
} 

$countable = new CountMe(); 
echo count($countable); 
//返回3


ArrayAccess接口
ArrayAccess {
 abstract public boolean offsetExists(mixed $offset)
 abstract public mixed offsetGet(mixed $offset)
 public void offsetSet(mixed $offset, mixed $value)
 public void offsetUnset(mixed $offset)
}


class CountMe
{ 
 protected $_myCount = 3; 

 public function count() 
 { 
  return $this->_myCount; 
 } 
} 

$countable = new CountMe(); 
echo count($countable);
//返回1

class CountMe implements Countable
{ 
 protected $_myCount = 3; 

 public function count() 
 { 
  return $this->_myCount; 
 } 
} 

$countable = new CountMe(); 
echo count($countable); 
//返回3

ArrayAccess 인터페이스

ArrayAccess {
 abstract public boolean offsetExists(mixed $offset)
    abstract public mixed offsetGet(mixed $offset)
    public void offsetSet(mixed $offset, mixed $value)
    public void offsetUnset(mixed $offset)
}

이 인터페이스의 기능은 다음을 허용하는 것입니다. 어떻게 말해야 할까요? 실제로 PHP는 어휘 분석 중에 배열 기반 개체를 만나면 해당 개체로 돌아가서 ArrayAccess가 구현되어 있는지 확인합니다. 해당 작업(set, unset, isset, get)을 수행하므로 클래스에 배열을 배치하고 클래스가 배열의 기본 작업을 구현하도록 할 수 있습니다.

class myObj
{
 
}
$obj = new myObj;
$obj['name'];
//Fatal error: Cannot use object of type myObj as array in 

class myObj implements ArrayAccess 
{
 public function offsetSet($offset, $value)
 {
  echo "offsetSet : {$offset} => {$value}\n";
 }

 public function offsetExists($offset)
 {
  echo "offsetExists : {$offset}\n";
 }

 public function offsetUnset($offset)
 {
  echo "offsetUnset : {$offset}\n";
 }

 public function offsetGet($offset)
 {
  echo "offsetGet : {$offset}\n";
 }
}
$obj = new myObj;
$obj[1] = '燕睿涛';
isset($obj['name']);
unset($obj['name']);
$obj['yrt'];

//输出结果:
offsetSet : 1 => 燕睿涛
offsetExists : name
offsetUnset : name
offsetGet : yrt

class myObj implements ArrayAccess 
{
 private $_data = [];
 public function offsetSet($offset, $value)
 {
  $this->_data[$offset] = $value;
 }

 public function offsetExists($offset)
 {
  return isset($this->_data[$offset]);
 }

 public function offsetUnset($offset)
 {
  unset($this->_data[$offset]);
 }

 public function offsetGet($offset)
 {
  return $this->_data[$offset];
 }
}

$obj = new myObj;
$obj['yrt'] = '燕睿涛';
var_dump($obj['yrt']);
var_dump(isset($obj['yrt']));
unset($obj['yrt']);
var_dump(isset($obj['yrt']));
var_dump($obj['yrt']);

//输出:
string(9) "燕睿涛"
bool(true)
bool(false)
Notice: Undefined index: yrt //最后一个会报出Notice

위 개체는 다음과 같습니다. 순회가 아닌 기본 배열 작업에 사용됩니다. 이전 IteratorAggregate와 결합하면 foreach:

class myObj implements ArrayAccess, IteratorAggregate
{
private $_data = [];

 public function getIterator()
 {
  return new ArrayIterator($this->_data);
 }

 ......
}
$obj = new myObj;
$obj['yrt'] = '燕睿涛';
$obj[1] = '燕睿涛';
$obj['name'] = '燕睿涛';
$obj['age'] = 23;

foreach ($obj as $key => $value) {
 echo "{$key} => {$value}\n";
}
//输出:
yrt => 燕睿涛
1 => 燕睿涛
name => 燕睿涛
age => 23

Iterator 인터페이스:

Iterator extends Traversable {
    abstract public mixed current(void)
    abstract public scalar key(void)
    abstract public void next(void)
    abstract public void rewind(void)
    abstract public boolean valid(void)
}

내부적으로 자체 외부 반복자 또는 클래스 인터페이스를 반복할 수 있습니다. 공식 문서에서 제공하는 내용인데, 사실 얼핏 이해하기 어렵습니다. 인터페이스에서 구현한 함수는 trratorAggregate와 유사합니다. (문서: 외부 반복자 인터페이스 생성, 인터페이스가 직접 반복자를 반환함) , 그러나 이것은 클래스 정의에서 구현됩니다. 예를 들면 다음과 같습니다.

class myObj implements Iterator{

 private $_data = [];

 public function __construct(Array $arr)
 {
 $this->_data = $arr;
 }

 public function current()
 {
 return current($this->_data);
 }

 public function key()
 {
 return key($this->_data);
 }

 public function next()
 {
 next($this->_data);
 }

 public function rewind()
 {
 reset($this->_data);
 }

 public function valid()
 {
 return $this->key() !== NULL;
 }
}

$t = [
 'yrt' => '燕睿涛',
 'name' => '燕睿涛',
 false,
 '燕睿涛'
];
$obj = new myObj($t);

foreach ($obj as $key => $value) {
 echo "{$key} => ".var_export($value, true)."\n";
}
//输出:
yrt => '燕睿涛'
name => '燕睿涛'
0 => false
1 => '燕睿涛'

위는 Brother Bird에 대한 참조입니다. 테스트 질문(반복자 모드)에 대한 기사이지만 Brother Bird의 유효성 판단에는 약간 결함이 있습니다. false인 값은 잘립니다.

Summary
말을 많이 해도 아직 깨닫지 못한 것 같습니다. Yii2의 소스 코드를 살펴보는 것이 좋습니다. 읽고 나면 "오~ 정말 유용한 것 같다..."라는 느낌이 서서히 들 것입니다.

위 내용은 이 글의 전체 내용이므로 모든 분들의 학습에 도움이 되기를 바랍니다. 더 많은 관련 내용을 보시려면 PHP 중국어 웹사이트를 주목해주세요!

관련 추천:

PHP를 통해 현재 페이지 URL 기능을 얻는 방법

PHP 배경에서 사용자가 직접 입력하는 코드 분석을 피하는 방법

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

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