经常使用接口(Interface)的好处是,别人只要看你的接口就知道你的类实现了哪些功能提供了哪些方法。PHP 提供了一些内置的接口,用来解决一些典型的问题
今天介绍两个接口,Countable
和 Iterator
。
Countable (计数器接口)
Countable
接口很简单,如果你的类需要一个统计对象内部某些元素个数的方法你可以实现 Countable
接口
<?php
/**
* Author: shanhuhai
* Date: 2017/9/16 23:07
* Mail: 441358019@qq.com
*/
class User implements Countable {
private $container = [];
public function insert($name){
array_push($this->container, $name);
}
public function count(){
return count($this->container);
}
}
$user = new User();
$user->insert("Shanhuhai");
$user->insert("Wudy");
echo $user->count().PHP_EOL;
Iterator (迭代器接口)
如果你想让你的对象能够使用 foreach
将其中的某些数据循环出来,你可以将类实现 Iterator
接口。
下面的例子展现了当你的类继承 Iterator
接口后内部方法执行的细节,很神奇是不是,好像你的对象变成了一个数组一样,能够被循环打印出来。
<?php
/**
* Author: shanhuhai
* Date: 2017/9/16 23:07
* Mail: 441358019@qq.com
*/
class User implements Iterator {
private $position = 0;
private $container = array(
"Shanhuhai",
"Rudy",
"Nash",
);
public function __construct() {
$this->position = 0;
}
public function rewind() {
var_dump(__METHOD__);
$this->position = 0;
}
public function current() {
var_dump(__METHOD__);
return $this->container[$this->position];
}
public function key() {
var_dump(__METHOD__);
return $this->position;
}
public function next() {
var_dump(__METHOD__);
++$this->position;
}
public function valid() {
var_dump(__METHOD__);
return isset($this->container[$this->position]);
}
}
$it = new User;
foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
转载请注明:大后端 » PHP Countable 接口和 Iterator 接口