我正在尝试另一种方法来做到这一点:
public function index()
{
$faker = Faker\Factory::create('fr_FR');
$ideas = [];
for ($i = 1; $i <= rand(10, 50); $i++) {
$idea = new \stdClass;
$idea->id = $i;
$idea->author = $faker->name;
//...
$ideas[] = $idea;
}
}
我不想在循环中创建对象并分配属性,而是想从类创建对象,并$ideas[]使用 array_pad() 函数填充:
public function index()
{
$faker = Faker\Factory::create('fr_FR');
$ideas = [];
$idea = new class {
private $id;
private $author;
function __construct() {
$this->id = count($ideas) + 1;
$this->author = $faker->name;
}
};
array_pad($ideas, rand(10, 50), new $idea);
}
所以我需要从匿名类中访问$fakerand 。$ideas我尝试将它们传递给班级,如下所示:
$idea = new class($ideas, $faker) {
private $id;
private $author;
private $ideas
private $faker
function __construct($ideas, $faker) {
$this->id = count($ideas) + 1;
$this->author = $faker->name;
}
};
但我得到一个
函数 class@anonymous::__construct() 的参数太少,已传递 0 个参数
烙印99