[英]Access outer variables from anonymous class
我正在尝试另一种方法:
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;
}
}
Instead of creating object and assigning attributes in the loop, I would like to create the object from a class, and populate $ideas[]
with the array_pad() function:
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);
}
所以我需要从匿名的 class 访问$faker
和$ideas
。 我试图将它们传递给 class,如下所示:
$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;
}
};
但我得到一个
arguments 到 function class@anonymous::__construct() 太少,0 已通过
可悲的消息:您不能为此使用array_pad
。
您需要在此处应用以消除错误的修复程序:
// array_pad($ideas, rand(10, 50), new $idea);
array_pad($ideas, rand(10, 50), $idea); // remove new
既然你已经在这里做了新的:
$idea = new class($ideas, $faker) {
即使这将填补$ideas
。 它将一遍又一遍地存储对您的$idea
的相同引用。 这意味着如果您更改一个元素,则此更改将作用于所有元素(我想这是不需要的)。
为了让它工作,你必须使用一个循环,它为每个条目创建一个新的$idea
:
$faker = Faker\Factory::create('fr_FR');
$ideas = [];
for ($i = rand(10, 50); $i > 0; $i--) {
$ideas[] = new class($ideas, $faker) {
private $id;
private $author;
function __construct($ideas, $faker) {
$this->id = count($ideas) + 1;
$this->author = $faker->name;
}
};
}
工作示例。
而不是这样做
for ($i = 1; $i <= rand(10, 50); $i++)
最好这样做
for ($i = rand(10, 50); $i > 0; $i--)
原因是每个循环都会调用比较,因此您会在每个循环上生成一个新的随机数。 例子
这是有问题的,因为您往往会得到更多这样的低数字。 例如,要获得 50 个循环,随机必须每次都返回> $i
- 这是不太可能的。
还有一件事: array_pad返回填充的数组,所以你必须写
$ideas = array_pad(...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.