PHP数组对象的属性 [英] php array object property

查看:119
本文介绍了PHP数组对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我与我的code解释我的问题。这工作:

Let me explain my problem with my code. This works:

$multiarray = array(
    'multikey1' => '',
    'multikey2' => ''
);
$array = array(
    'key1' => '',
    'key2' => '',
    'key3' => '',
    'key4' => $multiarray 
);
print_r($array);

这不工作:

class Array {

    public static $multiarray = array(
        'multikey1' => '',
        'multikey2' => '',
        'multikey3' => ''
    );

    public $array = array(
        'key1' => '',
        'key2' => self::$multiarray
    );
}

$array = new Array;

这不可惜工作。任何想法如何解决这个问题?

This does not work unfortunately. Any idea how to solve this?

推荐答案

您不能初始化成员变量任何不是常数,你想有另一个数组作为成员变量,这就需要运行时执行。

You can't initialize member variables to anything that is not constant, and you're trying include another array as a member variable, which would require runtime execution.

另外请注意,阵列类名是无效的,因为它与保留字阵列用于制造矛盾阵列

Also note that the Array class name is invalid, as it conflicts with the reserved word array used to create an array.

手动:

这声明可能包括初始化,但这
  初始化必须是一个恒定值 - 即,它必须能够
  在编译时进行评估,不能依赖于运行时间
  为了信息进行评估。

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

解决方法是设置在构造函数变量:

The workaround is to set your variable in the constructor:

class Array2 {
    public static $multiarray = array(
        'multikey1' =>  '',
        'multikey2' =>  '',
        'multikey3' =>  ''
    );

    public $array;

    function __construct() {
        $this->array = array(
            'key1'  =>  '',
            'key2'  =>  self::$multiarray
        );
    }
}

这篇关于PHP数组对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆