I'm trying to understand static property behavior in an abstract class.this is an example code retrieved from php object patterns and practice book (chapter 11-decorative pattern) :
abstract class Expression {
private static $keycount=0;
private $key;
function getKey() {
if ( ! isset( $this->key ) ) {
self::$keycount++;
$this->key=self::$keycount;
}
return $this->key;
}
}
a number of sub classes are extended from this abstract class and then getKey()
method will be called at instantiating time.each one check its own $key
property and if its null ,then increase $keycount
by one and assign it to $key
property .
as i understand $keycount
save its last value regardless of which subclass its running on . i mean it is in the context of abstract class NOT the context of sub classes. if it was dependent to its subclass then it would be reset to 0
in each subclass.can anyone provide me more insight into this ?
It looks like you answer your own question.
as i understand $keycount save its last value regardless of which subclass its running on
Yes, it works this way. The $keycount
is shared between all subclasses. Here is a simple test to check this behavior:
<?php
abstract class Expression {
private static $keycount=0;
private $key;
function getKey() {
if ( ! isset( $this->key ) ) {
self::$keycount++;
$this->key=self::$keycount;
}
return $this->key;
}
}
class ChildOne extends Expression {
}
class ChildTwo extends Expression {
}
$one = new ChildOne();
print 'One get key: ' . $one->getKey().PHP_EOL;
print 'One get key: ' . $one->getKey().PHP_EOL;
$oneMore = new ChildOne();
print 'One more get key: ' . $oneMore->getKey().PHP_EOL;
print 'One more get key: ' . $oneMore->getKey().PHP_EOL;
$two = new ChildTwo();
print 'Two get key: ' . $two->getKey().PHP_EOL;
print 'Two get key: ' . $two->getKey().PHP_EOL;
Output:
One get key: 1
One get key: 1
One more get key: 2
One more get key: 2
Two get key: 3
Two get key: 3