我有一个类,比如下面的
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")