
Originally Posted by
Dean C
Am I on the right track?
Static Methods, also called Class Method are for implementing behaviors which affect all instances of a class, rather than just a single instance.
PHP Code:
class Item {
protected static $count=0;
protected $name;
function __construct($name) {
$this->name = $name;
++self::$count;
}
function sayHello() {
return 'Hello from '.$this->name;
}
static function numItems() {
return self::$count;
}
}
class MiscTestCase extends UnitTestCase {
function testItem() {
$bob = new Item('Bob');
$this->assertEqual('Hello from Bob', $bob->sayHello());
$this->assertEqual(1,$bob->numItems());
$joe = new Item('Joe');
$this->assertEqual('Hello from Joe', $joe->sayHello());
$this->assertEqual(2,$joe->numItems());
}
}
What does not belong as a static class method is
PHP Code:
class Item {
static function lcase($str) {
return strtolower($str);
}
}
It just has no relation to the purpose of the Item class.
Bookmarks