【发布时间】:2020-07-18 17:57:35
【问题描述】:
我正在尝试另一种方法:
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;
}
}
我不想在循环中创建对象和分配属性,而是从一个类中创建对象,并使用 array_pad() 函数填充$ideas[]:
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);
}
所以我需要从匿名类访问$faker 和$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 已通过
【问题讨论】:
标签: php class anonymous-class