在构造函数中分配数组参数

时间:2013-02-13 14:20:57

标签: php

现在我正处于这样的环境中,我需要在函数中传递数组的参数(这样我可以根据我的需要在函数中覆盖它)。那怎么可能在PHP中。例如,

class classname
{
    function __construct()
    {
        $array['default'] = 'default value';
    }

    function test()
    {
        $array['a'] = 'a';
        $array['b'] = 'b';
    }
}

我需要在功能测试中获得$array['default']。那么如何在PHP中做到这一点?对此的任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

您希望$array成为对象属性:

class classname
{
    protected $array = array();

    function __construct()
    {
        $this->array['default'] = 'default value';
    }

    function test()
    {
        $this->array['a'] = 'a';
        $this->array['b'] = 'b';
    }
}

答案 1 :(得分:1)

你必须先在类中定义数组

班级考试{

$阵列=阵列();

function __construct()
{
    $this->array['default'] = 'default value';
}

function test()
{
    $this->array['a'] = 'a';
    $this->array['b'] = 'b';
}

}

答案 2 :(得分:0)

尝试,$this

class classname
{
    public $array;

    function __construct()
    {
        $this->array['default'] = 'default value';
    }

    function test()
    {
        $this->array['a'] = 'a';
        $this->array['b'] = 'b';
    }
}