从变量PHP OOP向数组添加项

时间:2017-01-08 01:55:12

标签: php arrays oop

我正在尝试从变量中将项添加到数组中。

class MyClassName {
public $key = '1234abcd';
public $email = 'example@example.tld';

var $header = array(
    "Content-Type: application/json",
    "KEY: " . $this->key,
    "EMAIL: " . $this->email
);  // code continued .....

出于某种原因,当我运行该代码时,它会给我一个错误syntax error, unexpected '$this' (T_VARIABLE)

我是否错误地分配了变量?

1 个答案:

答案 0 :(得分:0)

使构造函数解决了@joaumg -

所提到的问题
public $key = '1234abcd';
public $email = 'example@example.tld';
public $header = array();

function __construct() {
    $this->header = array(
        "Content-Type: application/json",
        "KEY: " . $this->key,
        "EMAIL: " . $this->email
    );
}

php.net/manual/en/language.oop5.decon.php