【问题标题】:defining a php constant value with a function in a class用类中的函数定义 php 常量值
【发布时间】:2015-02-10 21:45:39
【问题描述】:

可以在类中用函数定义php数组常量吗?

编辑:“php 数组变量”不是常量

我试过了:

假设, array func(string param1, string param2...);

class A{

    public static $const;

    public function blah(){
        self::$const = func('a','b','c',...);
    }
}

sublime 中的调试器在 self::$const 行的断点后没有显示 $const 的值

【问题讨论】:

  • '用函数定义一个常数' - 这不是矛盾吗?
  • @HoboSapiens 它不是。对于常量意味着它是不可变的,并且没有必要在编译时定义。
  • @CharlieS。这似乎在课堂上不起作用。
  • @HoboSapiens。我的意思是使用函数来定义常量或变量

标签: php arrays class constants


【解决方案1】:

在 PHP

如果您希望通过函数返回一个常量,您只需这样做:

define('FOO', 'bar')

function getFoo() {
  return FOO;
}

但这不是返回一个数组,这是一个非常愚蠢的例子。

我认为你真正想做的是从类的静态方法返回一个数组,类似于:

class Foo {
  public static function GetFoo() {
    return array(1, 2, 3);
  }
}

Foo::GetFoo();

或者如果你想将函数作为对象实例的方法运行,你不会设置静态属性(这对我来说没有意义)。

class Foo {
  private $foo = array();

  public function getFoo($arg1, $arg2) { // not sure what your arguments are for if this is intended to be a "constant"...
    $this->foo = array(...)
    return $this->foo
  }
}

$someFoo = new Foo();
$someFoo->getFoo(1, 2);

这有帮助吗? PHP Constants Containing Arrays? 的众多示例也应该有所帮助。

【讨论】:

  • 如果我在另一个公共静态函数中使用第二种方法中的数组,我会以 $this->GetFoo[index] 的形式访问它吗?
  • 好吧,在这种情况下,它似乎真的是一个单例,而不是一个常量,所以您不想定义您的单例并保留它以供任何需要的方法使用吗?
猜你喜欢
  • 1970-01-01
  • 2011-08-19
  • 1970-01-01
  • 2011-12-27
  • 2012-03-20
  • 1970-01-01
  • 2011-07-28
  • 2015-07-21
  • 1970-01-01
相关资源
最近更新 更多