1

我有一个名称很长的静态类,例如:

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 上。

4

3 回答 3

1

好吧,对于特定问题,只需将常量值分配给一个较短的变量并将其用作您的索引键。

$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);
于 2012-01-02T17:29:26.150 回答
1
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

于 2012-01-02T17:31:34.213 回答
1
class scwavln extends SomeClassWithAVeryLongName {}
$someArray[scwavln::CONST_ONE][scwavln::CONST_TWO] = 'foobar';
于 2012-01-02T17:33:21.920 回答