Why can't PHP have a constant object? -
i have key-value database table, store settings.
i have these settings in php constant object, since shouldn't editable.
in php7 can this:
define('mysettings', array( 'title' => 'my title' // etc )); // , call echo mysettings['title'];
and works great.
but why can't do:
define('mysettings', (object) array('title' => 'my title'));
so call instead:
echo mysettings->title; // or echo mysettings::title;
this because think it's quicker , prettier type object property/constant ($obj->key
, $obj::key
), array ($array['key']
)
is there reason not possible?
for php, objects mutable. since constants should never change @ runtime objects can, object-constants not supported.
in phpdoc constants, stated that:
when using const keyword, scalar data (boolean, integer, float , string) can contained in constants prior php 5.6. php 5.6 onwards, possible define constant scalar expression, , possible define array constant. possible define constants resource, should avoided, can cause unexpected results.
there inconsistency arrays though , no rational given why array constants allowed. (i argue bad call.) must noted array-constants
immutable, hence trying change them results in fatal error showcased code php7:
<?php $anormalmutablearray = ['key' => 'original']; $anormalmutablearray['key'] = 'changed'; echo $anormalmutablearray['key']; define( 'immutable_array', [ 'key' => 'original', ] ); immutable_array['key'] = 'if array, change; if constant throw error'; echo immutable_array['key'];
throwing:
php fatal error: cannot use temporary expression in write context in ~/wtf.php on line 12
why isn't possible define object constants similar error? 1 has ask power be.
i recommend staying away arrays , objects constants. rather create immutable objects or use immutable collections instead.
since looking syntax, there concept of class constants.
<?php class myclass { const constant = 'constant value'; function showconstant() { echo self::constant . "\n"; } } echo myclass::constant . "\n"; $classname = "myclass"; echo $classname::constant . "\n"; // of php 5.3.0 $class = new myclass(); $class->showconstant(); echo $class::constant."\n"; // of php 5.3.0
it's possible define them in interfaces.
Comments
Post a Comment