我想要做的是用循环填充参数。
这里是obj:
class Foo {
public $foovar1
public $foovar2
public $foovar3
public function __construct($foopara1, $foopara2, $foopara3) {
$this->foovar1 = $foopara1;
$this->foovar2 = $foopara2;
$this->foovar3 = $foopara3;
}
}
现在魔术:
<php?
/*$foo = new Foo( HERE I WANT TO DO A LOOP );*/
//But don't work...
$foo = new Foo(
for ($i=0; $i < 3; $i++) {
echo 'foopara.$i.,';
}
);
?>
这是错误:(!)解析错误:语法错误,意外'换'(T_FOR),期待')'
答案 0 :(得分:1)
<?php
class Foo {
public $foovar1;
public $foovar2;
public $foovar3;
public function __construct($foopara1, $foopara2, $foopara3) {
$this->foovar1 = $foopara1;
$this->foovar2 = $foopara2;
$this->foovar3 = $foopara3;
}
}
$class = new ReflectionClass('Foo');
$instance = $class->newInstanceArgs(range(0,2));
var_dump($instance);
/*
object(Foo)[2]
public 'foovar1' => int 0
public 'foovar2' => int 1
public 'foovar3' => int 2
*/
答案 1 :(得分:1)
请不要这样。这不是一个好的逻辑。如果你想要循环使用动态属性,为什么不这样做呢?
class Foo {
protected $vars = array();
public __construct($vars){
$this->vars = $vars;
}
// or even better:
public addVar($var){
$this->var[] = $var;
}
public getVar($idx){
return isset($this->var[$idx]) ? $this->var[$idx] : null;
}
}
$Bar = new Foo();
for($i=0;$i<10;$i++)
$Bar->addVar("something");
或者,如果您想要一个真正好的解决方案,请实现ArrayAccess接口和/或IteratorInterface。