
Originally Posted by
BerislavLopac
No, it would still be a class value, which is the whole point. Consider this:
PHP Code:
class Animal
{
protected static $coverage = 'skin';
public function getCoverage()
{
return self::$coverage;
}
}
class Bear extends Animal
{
protected static $coverage = 'fur';
}
$f = new Bear();
echo $f->getCoverage();
So all our animals are covered in skin...
Hmmm. AFIAC that is not an appropriate use of statics. You really want an instance object (and data) in this case; yes, you can specialize behaviour of static classes (which is the point of using statics in the first place -- encapsulization of pure behaviour) but because static data is tied to the defining class, you probably should not use statics to hold specializations of class data.
Again, static data is bound to the defining class only and I agree that the way self:: works is rather funky. Let us reconsider some different versions of your example:
PHP Code:
class Animal
{
protected static $coverage = 'skin';
public function getCoverage() { return self::$coverage . "\n"; }
}
class Fish extends Animal
{
protected static $coverage = 'scales';
public function setCoverage($coverage) { self::$coverage = $coverage; }
}
$a = new Animal;
$f = new Fish;
echo $a->getCoverage();
echo $f->getCoverage();
$f->setCoverage('scales');
echo $a->getCoverage();
echo $f->getCoverage();
That prints something you might not expect:
skin
skin
skin
skin
However, if you either change setCoverage() to use parent:: instead of self:: (so it points to the proper static data) or you remove the protected static $coverage = 'scales'; line -- then you get:
skin
skin
scales
scales
probably also unexpected. Finally:
PHP Code:
class Animal
{
protected static $coverage = 'skin';
public function getCoverage() { return self::$coverage . "\n"; }
}
class Fish extends Animal
{
protected static $coverage = 'scales';
public function getCoverage() { return self::$coverage . "\n"; }
}
}
$a = new Animal;
$f = new Fish;
echo $a->getCoverage();
echo $f->getCoverage();
yields:
skin
scales
So you can see is that depending on the class where the self:: is defined (as opposed to where in the hierarchy it is called from), you end up pointing to different (probably unexpected) static data. Statics are very unlike objects in this way.
Never-the-less, I can't imagine using static data on an object instance -- it makes no sense to me to do so. ie. use static data for static classes and expect that the data will be shared across the hierarchy. Then again, I don't see much point in extending static classes. If there is need for specialization, that structure is probably a better candidate to be an object.
Best Regards.
Bookmarks