在PHP中动态访问类常量
我希望能够动态地查找常量的值,但是使用变量与语法不兼容在PHP中动态访问类常量,php,constants,class-constants,Php,Constants,Class Constants,我希望能够动态地查找常量的值,但是使用变量与语法不兼容 <?php class Food { const FRUITS = 'apple, banana, orange'; const VEGETABLES = 'spinach, carrot, celery'; } $type = 'FRUITS'; echo Food::FRUITS; echo Food::$type; ?> 如何动态调用常量?我想到的唯一解决方案是使用常量函数: echo consta
<?php
class Food {
const FRUITS = 'apple, banana, orange';
const VEGETABLES = 'spinach, carrot, celery';
}
$type = 'FRUITS';
echo Food::FRUITS;
echo Food::$type;
?>
如何动态调用常量?我想到的唯一解决方案是使用常量函数:
echo constant('Food::' . $type);
在这里,您创建一个常量的名称,包括类,作为字符串,并将该字符串“Food::FRUITS”传递给常量函数。我想到的唯一解决方案是使用常量函数:
echo constant('Food::' . $type);
在这里,您可以创建一个常量(包括类)的名称作为字符串,并将该字符串“Food::FRUITS”传递给常量函数。可以使用ReflectionClass获取所有常量的数组,然后可以从中找到特定常量的值:
<?php
class Food {
const FRUITS = 'apple, banana, orange';
const VEGETABLES = 'spinach, carrot, celery';
}
$type = 'FRUITS';
$refClass = new ReflectionClass('Food');
$constants = $refClass->getConstants();
echo $constants[$type];
?>
ReflectionClass可用于获取所有常量的数组,然后可以从中找到特定常量的值:
<?php
class Food {
const FRUITS = 'apple, banana, orange';
const VEGETABLES = 'spinach, carrot, celery';
}
$type = 'FRUITS';
$refClass = new ReflectionClass('Food');
$constants = $refClass->getConstants();
echo $constants[$type];
?>
使用名称空间时,确保包含名称空间,即使它是自动加载的
namespace YourNamespace;
class YourClass {
public const HELLO = 'WORLD';
}
$yourConstant = 'HELLO';
// Not working
// >> PHP Warning: constant(): Couldn't find constant YourClass::HELLO ..
constant('YourClass::' . $yourConstant);
// Working
constant('YourNamespace\YourClass::' . $yourConstant);```
使用名称空间时,确保包含名称空间,即使它是自动加载的
namespace YourNamespace;
class YourClass {
public const HELLO = 'WORLD';
}
$yourConstant = 'HELLO';
// Not working
// >> PHP Warning: constant(): Couldn't find constant YourClass::HELLO ..
constant('YourClass::' . $yourConstant);
// Working
constant('YourNamespace\YourClass::' . $yourConstant);```
可以创建关联数组
class Constants{
const Food = [
"FRUITS " => 'apple, banana, orange',
"VEGETABLES" => 'spinach, carrot, celery'
];
}
和这样的访问值
$type = "FRUITS";
echo Constants::Food[$type];
可以创建关联数组
class Constants{
const Food = [
"FRUITS " => 'apple, banana, orange',
"VEGETABLES" => 'spinach, carrot, celery'
];
}
和这样的访问值
$type = "FRUITS";
echo Constants::Food[$type];
我想你不能,我想你不能。使用ReflectionClass获取所有常量的数组是以编程方式查找值的另一种方法。我希望有一些晦涩难懂的语法可以用一个语句/动作抓住值。使用ReflectionClass获取所有常量的数组是以编程方式查找值的另一种方法。我希望有一些晦涩的语法可以用一个语句/动作来获取值。