如何将多个值传递给类?

时间:2015-10-10 17:20:29

标签: php function class oop

我可以将一个值传递给类:

class Foo {

    public $value1;

    function __construct($var1) {
        $this->value1 = $var1;
    }
}

$foo = new Foo('value1');
print_r($foo);

如您所知,输出将如下:

Foo Object ( [value1] => value1 )

现在我想知道,我怎样才能将多个值传递给类?其实我想要这个输出:

Foo Object ( [value1] => value1, [value2] => value2, [value3] => value3 )

5 个答案:

答案 0 :(得分:3)

使用数组提交多个值。并添加输出函数,如:

class Foo {
    public $values = array();

    function __construct($values) {
        $this->values = $values;
    }

    function output() {
        foreach ($this->values as $key => $value) {
            echo $value . "\n";
        }
    }
}

$values = ["one", "two", "three"];
$f = new Foo($values);
$f->output();

答案 1 :(得分:2)

传递多个值可以完成如下操作:

function __construct($var1, $var2, $var3) {
    $this->value1 = $var1;
    $this->value2 = $var2;
    $this->value3 = $var3;
}

另一种选择是使用array作为参数:

function __construct($array_values) {
    $this->ar_values = $array_values;
}

function getValue($key)
{
    echo $this->ar_values[$key];
}


$foo = new Foo(array('value1','value2','value3'));
$foo->getValue(1);    // echoes 'value2'

更进一步,__construct的参数数量未知:

function __construct() {
    $args = func_get_args();
    print_r($args);
    // do something with this array
}

答案 2 :(得分:1)

除非我误解你,否则你可以通过将更多参数传递给构造来实现,如:

class Foo {

public $value1;
public $value2;
public $value3;

function __construct($var1, $var2, $var3) {
    $this->value1 = $var1;
    $this->value2 = $var2;
    $this->value3 = $var3;
  }
}

$foo = new Foo('value1', 'value2', 'value3');

答案 3 :(得分:1)

只需传递更多参数。

class Foo {

public $value1;
public $value2;
public $value3;

function __construct($var1,$var2,$var3) {
    $this->value1 = $var1;
    $this->value2 = $var2;
    $this->value3 = $var3;   

}
}

$foo = new Foo('value1','value2','value3');
print_r($foo);

答案 4 :(得分:1)

您只需使用逗号分隔其他值,并且为了向后兼容,您可以提供默认值。

function __construct($var1,$var2=null,$var3=null) {
    $this->value1 = $var1;
    $this->value2 = $var2;
    $this->value3 = $var3;
}

这样称呼;

$foo = new Foo('value1','value2','value3');