note 78292 modified in language.oop5.constants by danbrown
| From: | danbrown@php.net | Date: | Wed, 03 Aug 2011 13:29:34 +0000 |
| Subject: | note 78292 modified in language.oop5.constants by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-182177@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:
<?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.
--was--
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.
http://php.net/manual/en/language.oop5.constants.php