我有一个名称很长的静态类,例如:
class SomeClassWithAVeryLongName {
const CONST_ONE = 'foo';
const CONST_TWO = 'bar';
}
在我的另一门课中,我想引用这些常量。问题是有一堆,我将它们用作关联键,所以我的代码变得非常冗长:
$someArray[SomeClassWithAVeryLongName::CONST_ONE][SomeClassWithAVeryLongName::CONST_TWO] = 'foobar';
有没有办法使用某种指针?像这样:
// Pseudo code
$scwavln = 'SomeClassWithAVeryLongName';
$someArray[$scwavln::CONST_ONE][$scwavln::CONST_TWO] = 'foobar';
它似乎对我不起作用。我使用的是 PHP 5.2.6。
class scwavln extends SomeClassWithAVeryLongName {}
$someArray[scwavln::CONST_ONE][scwavln::CONST_TWO] = 'foobar';
好吧,对于特定问题,只需将常量值分配给一个较短的变量并将其用作索引键。
$index1 = SomeClassWithAVeryLongName::CONST_ONE;
$index2 = SomeClassWithAVeryLongName::CONST_TWO;
$someArray[$index1][$index2] = 'foo';
但是,您可以执行尝试使用 PHP 5.3 执行的操作:
$Uri = '''My''Namespaced''Class';
// you see the value of the const
var_dump($Uri::MY_CONST);
class SomeClassWithAVeryLongName {
const CONST_ONE = 'foo';
const CONST_TWO = 'bar';
}
$rfl = new ReflectionClass("SomeClassWithAVeryLongName");
$props = $rfl->getConstants();
print_r( $props );
Array
(
[CONST_ONE] => foo
[CONST_TWO] => bar
)
http://php.net/manual/en/class.reflectionclass.php