note 78292 deleted from language.oop5.constants by cmb

From: Date: Wed, 31 Aug 2016 17:18:48 +0000
Subject: note 78292 deleted from language.oop5.constants by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-206443@lists.php.net to get a copy of this message
Note Submitter: nrg1981 {AT} hotmail {DOT} com ---- If you have a class which defines a constant which may be overridden in child definitions, here are two methods how the parent can access that constant: <?php class Weather { const danger = 'parent'; static function getDanger($class) { // Code to return the danger field from the given class name } } class Rain extends Weather { const danger = 'child'; } ?> The two options to place in the parent accessor are: eval('$danger = ' . $class . '::danger;'); or: $danger = constant($class . '::danger'); I prefer the last option, but they both seem to work. So, why might this be useful? Well, in my case I have a page class which contains various common functions for all pages and specific page classes extend this parent class. The parent class has a static method which takes an argument (class name) and returns a new instantiation of the class. Each child class has a constant which defines the access level the user must have in order to view the page. The parent must check this variable before creating and returning an instance of the child - the problem is that the class name is a variable and $class::danger will treat $class as an object.

« previous php.notes (#206443) next »