Dynamische Konstante Name in PHP
-
10-10-2019 - |
Frage
Ich versuche, einen konstanten Namen dynamisch zu erstellen und dann auf dem Wert erhalten.
define( CONSTANT_1 , "Some value" ) ;
// try to use it dynamically ...
$constant_number = 1 ;
$constant_name = ("CONSTANT_" . $constant_number) ;
// try to assign the constant value to a variable...
$constant_value = $constant_name;
Aber ich finde, dass $ konstanter Wert noch den Namen des Konstante enthält, und nicht der Wert.
habe ich versucht, den zweiten Dereferenzierungsebene auch $$constant_name
Aber das wäre es eine Variable keine Konstante machen.
Kann jemand etwas Licht auf das werfen?
Lösung
http://dk.php.net/manual/en/function. constant.php
echo constant($constant_name);
Andere Tipps
Und zeigen, dass diese Arbeiten mit Klassenkonstanten auch:
class Joshua {
const SAY_HELLO = "Hello, World";
}
$command = "HELLO";
echo constant("Joshua::SAY_$command");
Um die dynamischen Konstante-Namen in Ihrer Klasse verwenden, können Sie Reflexion Funktion verwenden (da php5):
$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);
Zum Beispiel: wenn Sie Filter nur bestimmte (SORT_ *) Konstanten in der Klasse
class MyClass
{
const SORT_RELEVANCE = 1;
const SORT_STARTDATE = 2;
const DISTANCE_DEFAULT = 20;
public static function getAvailableSortDirections()
{
$thisClass = new ReflectionClass(__CLASS__);
$classConstants = array_keys($thisClass->getConstants());
$sortDirections = [];
foreach ($classConstants as $constName) {
if (0 === strpos($constName, 'SORT_')) {
$sortDirections[] = $thisClass->getConstant($constName);
}
}
return $sortDirections;
}
}
var_dump(MyClass::getAvailableSortDirections());
Ergebnis:
array (size=2)
0 => int 1
1 => int 2
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow