Iterating UTF-8 Strings
Learn about the UTF-8 string iterator implementation.
We'll cover the following...
Throughout the rest of this chapter, we will work to implement the following class that we can use to iterate UTF-8 strings:
Press + to interact
<?php$iterator = new Utf8StringIterator('這可以-this is fine!');foreach ($iterator as $char) {echo nl2br($char."\n");}
After our implementation is complete, the above will produce the following output:
Press + to interact
這可以-thisisfine!
Adding methods to an empty class
We will use all the techniques we’ve discussed so far, with the significant difference being the implementation details of various PHP interfaces. We will start with the following empty class and work to fill in all of the methods:
Press + to interact
<?phpuse Iterator;class Utf8StringIterator implements Iterator{protected $string = '';public function __construct(string $string){$this->string = $string;}public function current(){}public function next(){}public function key(){}public function valid(){}public function rewind(){}public function __toString(){return $this->string;}}
Our class accepts a string as part of its constructor and stores it internally. All of the class’s empty methods come from PHP’s Iterator
interface, which allows us to create ...