Posts

Showing posts with the label Constants

Abstract Constants In PHP - Force A Child Class To Define A Constant

Answer : This may be a bit of a ‘hack’, but does the job with very little effort, but just with a different error message if the constant is not declared in the child class. A self-referential constant declaration is syntactically correct and parses without problem, only throwing an error if that declaration is actually executed at runtime, so a self-referential declaration in the abstract class must be overridden in a child class else there will be fatal error: Cannot declare self-referencing constant . In this example, the abstract, parent class Foo forces all its children to declare the variable NAME . This code runs fine, outputting Donald . However, if the child class Fooling did not declare the variable, the fatal error would be triggered. <?php abstract class Foo { // Self-referential 'abstract' declaration const NAME = self::NAME; } class Fooling extends Foo { // Overrides definition from parent class // Without this declaration, an ...

Alternative For Define Array Php

Answer : From php.net... The value of the constant; only scalar and null values are allowed . Scalar values are integer, float, string or boolean values. It is possible to define resource constants, however it is not recommended and may cause unpredictable behavior. But You can do with some tricks : define('names', serialize(array('John', 'James' ...))); & You have to use unserialize() the constant value (names) when used. This isn't really that useful & so just define multiple constants instead: define('NAME1', 'John'); define('NAME2', 'James'); .. And print like this: echo constant('NAME'.$digit); This has changed in newer versions of PHP, as stated in the PHP manual From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant .