Background
This article demonstrates how to implement and use the Countable interface in PHP. The Countable interface is normally used in conjunction with other interfaces (i.e., Iterator, ArrayAccess, etc.) to create data structures like PHP SPL Library’s SplDoublyLinkedList and SplStack. Developers can create their own data structures by implementing several of these interfaces. The example on this post is pretty basic. By implementing Countable, we can use the PHP count() function on a Countable object to retrieve the “number of items.”
The Countable interface has one abstract method called count(). Classes that implement this interface must override this method by providing their implementation of count().
Software Requirements
- Windows 7 Professional SP1
- PHP 5.5.9 / Zend Engine v2.5.0
- NetBeans IDE 8.0.1
The Codes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | /* * Copyright 2014 www.turreta.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Description of CountableInterfaceSample * * @author www.turreta.com */ class CountableInterfaceSample implements Countable { private $names = array(); public function add($name) { $this->names[] = $name; } public function get($index) { return $this->names[$index]; } public function delete($index) { unset($this->names[$index]); } public function count($mode = 'COUNT_NORMAL') { return count($this->names); } } $list_like_data_structure = new CountableInterfaceSample(); $list_like_data_structure->add("Peter"); $list_like_data_structure->add("John"); $list_like_data_structure->add("Mark"); echo 'Count is: ' . count($list_like_data_structure) . "\n"; $list_like_data_structure->delete(1); echo 'Count is: ' . count($list_like_data_structure) . "\n"; print_r($list_like_data_structure); |
Sample Output
1 2 3 4 5 6 7 8 9 10 11 | Count is: 3 Count is: 2 CountableInterfaceSample Object ( [names:CountableInterfaceSample:private] => Array ( [0] => Peter [2] => Mark ) ) |
Get the Codes
https://github.com/Turreta/php-essentials/blob/master/spl%20libray/CountableInterfaceSample.php