美文网首页PHP
php预定义接口

php预定义接口

作者: taobao | 来源:发表于2020-12-17 09:38 被阅读0次

1、Traversable(遍历)接口

检测一个类是否可以使用 foreach 进行遍历的接口。
无法被单独实现的基本抽象接口。相反它必须由 IteratorAggregateIterator 接口实现。

$myarray = array('one', 'two', 'three');
$myobj = (object)$myarray;

if ( !($myarray instanceof \Traversable) ) {
    print "myarray is NOT Traversable";
}
if ( !($myobj instanceof \Traversable) ) {
    print "myobj is NOT Traversable";
}

foreach ($myarray as $value) {
    print $value;
}
foreach ($myobj as $value) {
    print $value;
}

Output:
myarray is NOT Traversable
myobj is NOT Traversable
one
two
three
one
two
three

2、Iterator(迭代器)接口

接口摘要:
Iterator extends Traversable {
/* 方法 */
abstract public current ( ) : mixed
abstract public key ( ) : scalar
abstract public next ( ) : void
abstract public rewind ( ) : void
abstract public valid ( ) : bool
}

<?php
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 getIterator ( ) : Traversable
}

<?php
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";
}
?>
以上例程的输出类似于:

string(9) "property1"
string(19) "Public property one"

string(9) "property2"
string(19) "Public property two"

string(9) "property3"
string(21) "Public property three"

string(9) "property4"
string(13) "last property"

4、ArrayAccess(数组式访问)接口

提供像访问数组一样访问对象的能力的接口。
接口摘要:
ArrayAccess {
/* 方法 */
abstract public offsetExists ( mixed $offset ) : boolean
abstract public offsetGet ( mixed $offset ) : mixed
abstract public offsetSet ( mixed $offset , mixed $value ) : void
abstract public offsetUnset ( mixed $offset ) : void
}

<?php
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);
?>
以上例程的输出类似于:

bool(true)
int(2)
bool(false)
string(7) "A value"
obj Object
(
    [container:obj:private] => Array
        (
            [one] => 1
            [three] => 3
            [two] => A value
            [0] => Append 1
            [1] => Append 2
            [2] => Append 3
        )

)

5、序列化接口

自定义序列化的接口。
实现此接口的类将不再支持 __sleep() 和 __wakeup()。不论何时,只要有实例需要被序列化,serialize 方法都将被调用。它将不会调用 __destruct() 或有其他影响,除非程序化地调用此方法。当数据被反序列化时,类将被感知并且调用合适的 unserialize() 方法而不是调用 __construct()。如果需要执行标准的构造器,你应该在这个方法中进行处理。
接口摘要
Serializable {
/* 方法 */
abstract public serialize ( ) : string
abstract public unserialize ( string $serialized ) : mixed
}

<?php
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);

$newobj = unserialize($ser);

var_dump($newobj->getData());
?>
以上例程的输出类似于:
string(15) "My private data"

6、Closure 类

用于代表 匿名函数 的类.

匿名函数(在 PHP 5.3 中被引入)会产生这个类型的对象。在过去,这个类被认为是一个实现细节,但现在可以依赖它做一些事情。自 PHP 5.4 起,这个类带有一些方法,允许在匿名函数创建后对其进行更多的控制。

除了此处列出的方法,还有一个 __invoke 方法。这是为了与其他实现了 __invoke()魔术方法 的对象保持一致性,但调用匿名函数的过程与它无关。

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

<?php
$deleteDirectory = null;
$deleteDirectory = function($path) use (&$deleteDirectory) {
    $resource = opendir($path);
    while (($item = readdir($resource)) !== false) {
        if ($item !== "." && $item !== "..") {
            if (is_dir($path . "/" . $item)) {
                $deleteDirectory($path . "/" . $item);
            } else {
                unlink($path . "/" . $item);
            }
        }
    }
    closedir($resource);
    rmdir($path);
};
$deleteDirectory("path/to/directoy");
?>

//bind
class A{
      private $name = '王力宏';
      protected $age = '30';
      private static $weight = '70kg';
      public $address = '中国';
      public static $height = '180cm';
  }
$fun = function(){
    //name是私有属性,需要第3个参数
    return $this->name;
} ;
$name = Closure::bind($fun,new A() ,'A');                                                                                                                                                           
echo $name();//输出 王力宏 
该函数返回一个全新的 Closure匿名的函数,和原来匿名函数$fun一模一样,只是其中$this被指向了A实例对象,这样就能访问address属性了。

7、生成器类

类摘要
Generator implements Iterator {
/* 方法 */
public current ( ) : mixed
public key ( ) : mixed
public next ( ) : void
public rewind ( ) : void
public send ( mixed $value ) : mixed
public throw ( Exception $exception ) : void
public valid ( ) : bool
public __wakeup ( ) : void
}

<?php
function fib($n)
{
    $cur = 1;
    $prev = 0;
    for ($i = 0; $i < $n; $i++) {
        yield $cur;

        $temp = $cur;
        $cur = $prev + $cur;
        $prev = $temp;
    }
}

$fibs = fib(9);
foreach ($fibs as $fib) {
    echo " " . $fib;
}

// prints: 1 1 2 3 5 8 13 21 34

相关文章

网友评论

    本文标题:php预定义接口

    本文链接:https://www.haomeiwen.com/subject/vlengktx.html