PHP predefined interface_PHP tutorial

WBOY
Release: 2016-07-13 09:45:38
Original
760 people have browsed it

PHP predefined interface

Introduction
There are several predefined interfaces in PHP, which are quite useful
IteratorAggregate(aggregate aggregate iteratorIterator)
IteratorAggregate extends Traversable {
abstract public Traversable getIterator(void)
}
This interface implements a function - creating an external iterator. How to understand it specifically? When we use foreach to traverse an object, if we do not inherit the IteratorAggregate interface, all public properties (only It can be in the form of public $var). If you inherit IteratorAggregate, the object returned by the getIterator method implemented in the class will be used. Note here that the returned object must be a Traversable object or an object extended from Traversable, otherwise an exception will be thrown
//看个例子
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)
}
Copy after login

This interface is used to count the number of objects. How to understand it specifically? When we call count on an object, if the function does not inherit Countable, it will always return 1. If it inherits Countable, it will return the value returned by the implemented count method. numbers, take a look at the example below:
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)
}
Copy after login

The function of this interface is to allow us to access objects like arrays. How do I put this? I guess it is actually that if PHP encounters an array when using an object during lexical analysis, it will go back to the object to find out whether there is an object. If there is one, implement ArrayAccess and perform the corresponding operations (set, unset, isset, get), so that we can place an array in the class and let the class implement the basic operations of the array. Here is an example:
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)
}
Copy after login

You can iterate your own external iterator or class interface internally. This is the explanation given by the official document. It is still difficult to understand. In fact, I feel that the function implemented by this interface is similar to that of traratorAggregate (document: Create external iterator interface, the interface directly returns an iterator) is similar, but this is implemented in the class definition. Take an example:
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 => '燕睿涛'
Copy after login

The above is a reference to an article by Brother Niao about a test question (Iterator mode), but Brother Niao’s judgment of valid is a bit flawed. When it encounters a value that is false, it will be truncated

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1039604.htmlTechArticleIntroduction to PHP predefined interfaces. There are several predefined interfaces in PHP, including the quite useful IteratorAggregate (aggregated aggregate iteratorIterator) IteratorAggregate extends Traversable...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template