亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從匿名類訪問外部變量

從匿名類訪問外部變量

PHP
慕勒3428872 2023-08-11 16:51:01
我正在嘗試另一種方法來做到這一點: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 個參數
查看完整描述

1 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

悲傷的消息:你不能用于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(...


查看完整回答
反對 回復 2023-08-11
  • 1 回答
  • 0 關注
  • 145 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號