note 98303 modified in class.countable by danbrown

From: Date: Tue, 08 Jun 2010 14:30:56 +0000
Subject: note 98303 modified in class.countable by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-169941@lists.php.net to get a copy of this message
I just want to point out that your class has to actually implement the Countable interface, not just define a count method, to be able to use count($object) and get the expected results. I.e. the first example below won't work as expected, the second will. (The normal arrow function accessor ($object->count()) will work fine, but that's not the kewl part :) ) <?php //Example One, BAD :( class CountMe { protected $_myCount = 3; public function count() { return $this->_myCount; } } $countable = new CountMe(); echo count($countable); //result is "1", not as expected //Example Two, GOOD :) class CountMe implements Countable { protected $_myCount = 3; public function count() { return $this->_myCount; } } $countable = new CountMe(); echo count($countable); //result is "3" as expected ?> --was-- I just want to point out that your class has to actually implement the Countable interface, not just define a count method, to be able to use count($object) and get the expected results. I.e. the first example below won't work as expected, the second will. (The normal arrow function accessor ($object->count()) will work fine, but that's not the kewl part :) ) //Example One, BAD :( class CountMe { protected $_myCount = 3; public function count() { return $this->_myCount; } } $countable = new CountMe(); echo count($countable); //result is "1", not as expected //Example Two, GOOD :) class CountMe implements Countable { protected $_myCount = 3; public function count() { return $this->_myCount; } } $countable = new CountMe(); echo count($countable); //result is "3" as expected http://php.net/manual/en/class.countable.php

« previous php.notes (#169941) next »