简体   繁体   中英

Yii2 $defaultValue in anonymous functions

Not a big problem,but i wanna figure it out why. I was reading at Yii2 By Example. And i noticed that view file in the exmaple of a db Transaction. it's about dropdownlist,here is the code:

<?= $form->field($reservation, "room_id")->
dropDownList(ArrayHelper::map(Room::find()->all(), 'id', 
function($room, $defaultValue) {
return sprintf('Room n.%d at floor %d', $room->room_number, $room->floor);
})); ?>

I tried it with and without the $defaultValue.Both worked. so what is the use of the "$defaultValue"? or it just a non-sence. I googled it and have no idea. Thank you for your time.

As you can see in the yii2 reference http://www.yiiframework.com/doc-2.0/yii-helpers-basearrayhelper.html#map()-detail

in the map() function of the ArrayHelper you can use for from, to and group param a clousure too ..

then in the clusere you can pass th the inner function a list o param that are "visible" inside the function in you case you don't use $defaultValue so you could avoid to pass this var

  ArrayHelper::map(Room::find()->all(), 'id', 
  function($room) {
  return sprintf('Room n.%d at floor %d', $room->room_number, $room->floor);
  })

You could use also $test var and use it eg:

  $test = 'Big ';
  ArrayHelper::map(Room::find()->all(), 'id', 
  function($room) use($test) {
  return sprintf( $test . 'Room n.%d at floor %d', $room->room_number, $room->floor);
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM