[英]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.