Magento 2: what is the $data array constructor parameter?
The $data[]
can be used to hold values passed from di.xml
's arguments replacement mechanism, when \Magento\Catalog\Block\Product\ListProduct
intantiated.
In your case this could be populated by
<type name="\Magento\Catalog\Block\Product\ListProduct">
<arguments>
<argument name="data" xsi:type="array">
<item name="0" xsi:type="string">anystring</item>
<item name="1" xsi:type="string">xyz</item>
<item name="2" xsi:type="string">abs</item>
</argument>
</arguments>
</type>
You can even pass object and other formats to an array using above di mechanism. Further you can use those arguments while extending functionality. We can say, it is a kind of va_list
in c.
This can be used when you don't want to modify the number of arguments in a constructor and want to inject other classes in your extended functionalities.
The $data
can be used to populate data on your object since the constructor of \Magento\Framework\DataObject
is this
public function __construct(array $data = [])
{
$this->_data = $data;
}
or similar for Magento\Framework\Api\AbstractSimpleObject
/**
* Initialize internal storage
*
* @param array $data
*/
public function __construct(array $data = [])
{
$this->_data = $data;
}
which a lot of classes in Magento extend from.
A common use is in conjunction with a factory. For example in
Magento\Sales\Model\Order\CustomerManagement
we have:
$this->addressFactory->create(['data' => $addressData]);
which essentially populates the $data
array at creation.
Having to keep the $data = []
at the end of the list of parameters is normal php behaviour since you are assigning a default value - the empty array.