2015-10-10 47 views
2

我可以一个值传递给类是这样的:如何将多个值传递给类?

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) 

回答

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'); 
+0

投票下来,因为? –

+1

谢谢,+1对你的赞赏。 – Shafizadeh

+1

每个人都因为某种原因被拒绝了。有些答案比其他答案好,但没有一个是错的。也许downvoter想解释。 – worldofjr

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); 
+1

谢谢+1,upvote – Shafizadeh

1

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

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

这样调用;

$foo = new Foo('value1','value2','value3'); 
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 
} 
+0

非常感谢,很好的回答,+1赞成你。 – Shafizadeh

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(); 
+0

其实它是重复了一下,但+1 – Shafizadeh

+1

我没有看到重复。没有人使用数组和输出函数。 – Sun

+2

还值得指出的是,如果您更改传入的参数数量,其他答案将需要您重写您的类。传入一个数组会更加整齐。 – andrewsi