Dynamic Constant Name in PHP

Dynamic constant name in PHP

http://dk.php.net/manual/en/function.constant.php

echo constant($constant_name);

making dynamic defined constants php

You need to call constant() to retrieve the value of a constant from a string. Your example should look like:

$error_code = 404;
define('E404', 'Not found');
echo constant("E{$error_code}");

and it will display Not found.

Dynamic constants in PHP?

Wrap your "enum" values in a singleton and implement the (non-static) magic __get method:

<?php
class DynamicEnums {

private static $singleton;

private $enum_values;

public static function singleton() {
if (!self::$singleton) {
self::$singleton = new DynamicEnums();
}
return self::$singleton;
}

function __construct() {
$this->enum_values = array( //fetch from somewhere
'one' => 'two',
'buckle' => 'my shoe!',
);
}

function __get($name) {
return $this->enum_values[$name]; //or throw Exception?
}

public static function values() {
return self::singleton()->enum_values; //warning... mutable!
}
}

For bonus points, create a (non-OO) function that returns the singleton:

function DynamicEnums() {
return DynamicEnums::singleton();
}

Consumers of "DynamicEnums" would look like:

echo DynamicEnums::singleton()->one;
echo DynamicEnums()->one; //can you feel the magic?
print_r(DynamicEnums::values());

[edit] More enum-like.

Get value of dynamically chosen class constant in PHP

Use the constant() function:

$id = constant("ThingIDs::$thing");

Is it possible to declare dynamic constants in Laravel models using records for the model?

You lack in basic programming knowledge.

A const variable is supposed to never change

A static variable is supposed to be accessed as class member without initializating class (using a new keyword)

A non-static non-const variable is accessible only after initializating a class with new keyword

You probably want to replace a bad

const $key = $val;

with

$this->$key = $val;

Which will work in Laravel

class Status extends BaseModel
{
protected $table = 'Status';

public function __construct(array $attributes) {
parent::__construct($attributes);

$records = [
'some_reflected_field_1' = 100,
'some_reflected_field_2' = 101,
'some_reflected_field_3' = 102
];

foreach($records as $key => val) {
$this->$key = $val;
}
}
}

Execution:

$foo = new Status([
'name' => 'active'
]);

echo $foo->some_reflected_field_2; // 101

Get a constant value from a string in PHP

Yes, you can get the value of a constant of computed name with the constant function:

define('CONNECTION_FAILED', 'Connection Error');
$success = $_GET['message']; //$success -> 'CONNECTION_FAILED'
$message = constant($success); // 'Connection error'


Related Topics



Leave a reply



Submit