note 78292 added to language.oop5.constants

From: Date: Fri, 05 Oct 2007 13:19:07 +0000
Subject: note 78292 added to language.oop5.constants
Groups: php.notes 
Request: Send a blank email to php-notes+get-131137@lists.php.net to get a copy of this message
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: 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. ---- Server IP: 212.24.129.51 Probable Submitter: 85.160.4.114 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.constants.php Edit -- https://master.php.net/note/edit/78292 Del: integrated -- https://master.php.net/note/delete/78292/integrated Del: useless -- https://master.php.net/note/delete/78292/useless Del: bad code -- https://master.php.net/note/delete/78292/bad+code Del: spam -- https://master.php.net/note/delete/78292/spam Del: non-english -- https://master.php.net/note/delete/78292/non-english Del: in docs -- https://master.php.net/note/delete/78292/in+docs Del: other reasons-- https://master.php.net/note/delete/78292 Reject -- https://master.php.net/note/reject/78292 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#131137) next »