【问题标题】:How to use list and array to instantiate fields in a class?如何使用列表和数组来实例化类中的字段?
【发布时间】:2012-07-10 08:41:05
【问题描述】:

我想同时实例化我的 PHP 类的每个字段。到目前为止,我已经尝试过使用list。这是我下面的代码(不起作用)。我们很乐意接受任何帮助。

class Test {
  private $x;
  private $y;
  private $z;

  public function Test() {
    $fields = array($this->x, $this->y, $this->z);
    // I need $fields to be an array here.
    list($fields) = array(1, 2, 3); // It would work if $fields wasn't an array.
    echo 'x = ' . $this->x . '<br />y = ' . $this->y . '<br />z = ' . $this->z;
  }
}

new Test();

【问题讨论】:

    标签: php arrays list


    【解决方案1】:
    list($this->x, $this->y, $this->z) = array(1, 2, 3);
    

    【讨论】:

    • 对不起,我忘记了代码中的一些信息。我需要$fields 来创建一个数组。
    • 为什么你需要它是一个数组?那你就不能用list()了。
    • 我在这里对数组做其他事情。
    • 很抱歉,list() 不适用于数组,您必须在 list() 中明确列出所有变量。如果这不是您想要的,您需要以传统方式分配值$this-&gt;x = 1; ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    相关资源
    最近更新 更多