Accessing child constants from base class

From: Date: Fri, 10 Oct 2003 07:10:23 +0000
Subject: Accessing child constants from base class
Groups: php.internals 
Request: Send a blank email to internals+get-4771@lists.php.net to get a copy of this message
PHP5 10/10/2003 CVS. Currently, I don't see an easy way of accessing the constants of a child class from a base class. Consider the following basic example: abstract class myBaseClass { function getXML() { $doc = new domDocument(); $node = $doc->createElement(child::ElementName); $doc->appendChild($node); return $doc->saveXML($node); } } class myChildClass extends myBaseClass { const ElementName = 'foo'; // ..lots of methods, etc here.. } $foo = new myChildClass(); print($foo->getXML()); Of course, this does not work as there is no 'child::' accessor. The alternatives to making this work are: Use a protected variable in the child (and, of course, don't forget to also say 'protected $ElementName;' in the base class) and use $this->ElementName for accessing the child's ElementName from the parent. This is probably good enough, but much less than ideal. Use this beautifully low maintenance, high performance piece of code in the base class (not): $className = get_class($this); switch($className) { case 'mychildclass': $childElementName = myChildClass::ElementName; break; case 'myotherchildclass': $childElementName = myOtherChildClass::ElementName; break; // etc..... } .... ick! You may be able to shortcut the need for the switch statement with some variable variable and/or eval() trickery, but let's not even go there.. So are there any plans on implementing child:: ? Is there a way of accessing child constants without having to explicitly known the current and/or child class name? Any input appreciated- Dan Cox

« previous php.internals (#4771) next »