note 69866 deleted from language.oop5.constants by cmb
| From: | cmb@php.net | Date: | Wed, 31 Aug 2016 17:14:20 +0000 |
| Subject: | note 69866 deleted from language.oop5.constants by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-206438@lists.php.net to get a copy of this message | ||
Note Submitter: webmaster at chaosonline dot de
----
Since constants of a child class are not accessible from the parent class via self::CONST and there
is no special keyword to access the constant (like this::CONST), i use private static variables and
these two methods to make them read-only accessible from object's parent/child classes as well
as statically from outside:
<?php
class b extends a {
private static $CONST = 'any value';
public static function getConstFromOutside($const) {
return self::$$const;
}
protected function getConst($const) {
return self::$$const;
}
}
?>
With those methods in the child class, you are now able to read the variables from the parent or
child class:
<?php
class a {
private function readConst() {
return $this->getConst('CONST');
}
abstract public static function getConstFromOutside($const);
abstract protected function getConst($const);
}
?>
From outside of the object:
<?php
echo b::getConstFromOutside('CONST');
?>
You maybe want to put the methods into an interface.
However, class b's attribute $CONST is not a constant, so it is changeable by methods inside of
class b, but it works for me and in my opinion, it is better than using real constants and accessing
them by calling with eval:
<?php
protected function getConst($const) {
eval('$value = '.get_class($this).'::'.$const.';');
return $value;
}
?>