Get Value of Dynamically Chosen Class Constant in PHP

Get value of dynamically chosen class constant in PHP

Use the constant() function:

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

How to access a class const dynamically in PHP?

The function constant does this. The syntax is

constant('Order::'.$status)

See it in action.

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.

Why the class constant value is getting evaluated in one statement and not in other?

Afaik this is not possible. The whole "variable parsing" (extended curly syntax) in strings is done base on variables. Variables always start with a $ sign, so not starting with a $ does not seem to work. (i.e. Everything which is not (part of) a variable cannot be used.).

Simplified example (which wont work):

const TEST = 'A & W';
echo "I'd like an {TEST}\n";

Same for function calls (which also do not work directly)

$test = '   A & W   ';
echo "I'd like an {trim($test)}\n";

Only in "sub" curly braces the desired output can be used, but it has to be parsed as a variable again which makes it impossible (at this point).

Does work:

$AW = 'A & W';
$test = ' AW ';
echo "I'd like an {${trim($test)}}\n";

Edit:

If you truly WANT to output a (class) constant inside a complex curly brace expression:

class beers {
const softdrink = 'rootbeer';
}

function foobar($test) {
$GLOBALS[$test] = $test;
return $test;
}

echo "I'd like an {${foobar(beers::softdrink)}}\n";

This is far from what I would recommend to do!!!

Dynamic constant name in PHP

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

echo constant($constant_name);

PHP: Class constants in type declarations of input paramaters

PHP doesn't have constant restrictions, only types.

But you can do a workaround like this:

class LogLevel
{
protected string $logName;

private function __construct(string $logName)
{
$this->logName = $logName;
}
public function getName(): string
{
return $this->logName;
}

public static function emergency(): self
{
return new self('emergency');
}

public static function alert(): self
{
return new self('alert');
}

public static function critical(): self
{
return new self('critical');
}
// create the other constants here
}

Now your static funcion works

public static function log($log, LogLevel $logLevel = null): void {
// .....
}

$logLevel will receive LogLevel::emergency(), LogLevel::critical(), etc. and you can get the level name just calling $logLevel->getName()

How to access static property and static constants of another Class Dynamically

comment line 11 and 12 and try to var_dump this->config and you'll see that it is not picking the whole object but just the __construct because you are calling static methods on an object so try the following code


        class HelloAction
{
const FIRST = "DEMO";
public static $first = "WORLD";
function __construct($confclassname)
{
$this->config = $confclassname;
# PHP Interpreter throws an Error for These Two Lines
$this->first1 = $confclassname::$a;
$this->first2 = $confclassname::$b;
}

function setFirst($s)
{
self::$first = $s;
}
}

class action1
{
const AAAA = "____Hello World____";
public static $a = "this is an apple";
public static $b = "That is an Dog";
function __construct()
{
$this->second = "hi, there.";
}
}

class action2
{
const AAAA = "___Yeah, Hello World____";
public static $a = "Whare You were...";
public static $b = "Awesome work";
function __construct()
{

}
public static function action21($s)
{
self::$a = $s;
}
public function action22()
{
return self::$a;
}
}

$b1 = new HelloAction('action1');
$b2 = new HelloAction('action2');

echo $b1->first1 . "\n";
echo $b1->first2 . "\n";

?>

Dynamic (Shell Exec) Defined Constant via Function in PHP

This is valid PHP, but it is NOT the same as calling the function each time (unless the function always returns the same result). Basically the function gets called when the define is encountered, and that return value is assigned to the constant. Consider:

function getv() {
static $v = 4;
return $v++;
}

define('V', getv());
echo V . PHP_EOL;
echo getv() . PHP_EOL;
echo V . PHP_EOL;

Output:

4
5
4

Note that the constant V always outputs 4, even after the return value of getv changes to 5.

Demo on 3v4l.org



Related Topics



Leave a reply



Submit