【问题标题】:PHP Static class has a very long name - can I use a shorter pointer?PHP 静态类的名称很长 - 我可以使用更短的指针吗?
【发布时间】:2012-01-31 23:27:37
【问题描述】:

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

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

【问题讨论】:

  • 代码的阅读频率远高于编写频率。因此,您应该尝试编写可读的代码。 $scwavln 不可读,所以不要这样做。
  • 愚蠢,这只是一个例子。实际的类名是Facebook_Open_Graph_API,我想用FBAPI

标签: php constants class-constants


【解决方案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);

【讨论】:

    【解决方案2】:
    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

    【讨论】:

      【解决方案3】:
      class scwavln extends SomeClassWithAVeryLongName {}
      $someArray[scwavln::CONST_ONE][scwavln::CONST_TWO] = 'foobar';
      

      【讨论】:

        猜你喜欢
        • 2021-05-07
        • 1970-01-01
        • 1970-01-01
        • 2012-07-22
        • 2021-01-24
        • 1970-01-01
        • 2018-05-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多