[英]Get constant value using variable name
我有一个像波纹管这样的课程,
namespace DTS\eBaySDK\Constants;
class SiteIds
{
// United States
const US = 0;
// Canada (English)
const ENCA = 2;
// UK
const GB = 3;
// Australia
const AU = 15;
// Austria
const AT = 16;
// Belgium (French)
const FRBE = 23;
// France
const FR = 71;
// Germany
const DE = 77;
// Motors
const MOTORS = 100;
// Italy
const IT = 101;
// Belgium (Dutch)
const NLBE = 123;
// Netherlands
const NL = 146;
// Spain
const ES = 186;
// Switzerland
const CH = 193;
// Hong Kong
const HK = 201;
// India
const IN = 203;
// Ireland
const IE = 205;
// Malaysia
const MY = 207;
// Canada (French)
const FRCA = 210;
// Philippones
const PH = 211;
// Poland
const PL = 212;
// Singapore
const SG = 216;
}
我可以如下访问
echo Constants\SiteIds::US;
但是当我尝试像下面这样访问时,它不起作用,
$country ='US';
echo Constants\SiteIds::$country;
有没有这样的访问方法?
尝试使用以下代码:
$ref = new ReflectionClass('DTS\eBaySDK\Constants\SiteIds');
$constName = 'US';
echo $ref->getConstant($constName);
我在以下位置找到了这个答案: stackoverflow.com
要使用变量获取常量,必须使用constant
函数。 该函数需要常量的完全限定名称 ,在您的情况下,该名称包括名称空间:
constant("DTS\eBaySDK\Constants\SiteIds::$country")
或从相同的名称空间中:
constant(__NAMESPACE__ . "\SiteIds::$country")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.