Reputation: 1490
I have the following piece of code, which generates six drop-down elements:
for($i = 0; $i < 6; $i++)
{
$RelatedProductsHtmlList .= $this->getRelatedProductHtmlDropdown($Products[$i], $allAvailibleProducts, $i);
}
In this code, the argument $Products[$i]
is passed, which is a ORM object with information for setting the default selected value of the drop-down list that is generated. I have the problem that $Products
is not always an array. Sometimes only contains one value, in which case it's not an array, but a single ORM object.
What is the cleanest thing to do? Convert $Products
to an array with only one element? Always pass the entire $Products
variable en determine in the function if it's an array? Or determine if $Products
is an array before calling the function and set the function argument accordingly?
Upvotes: 1
Views: 62
Reputation: 4984
I would suggest to allow to pass array and a single object into a function. You will avoid multiple checks in different parts of code. You can do it this way:
/**
@param array | ProductClass $Products
...
*/
public function getRelatedProductHtmlDropdown($Products, $allAvailibleProducts, $i)
{
if (!is_array($Products)) $Products = array($Products);
....
}
Upvotes: 0
Reputation: 157947
You have two options: fix it before calling the method or inside the method itself.
Example:
if(!is_array($products)) {
$products = array($product));
}
If you ask me, I would add this code to the top of the method itself as this would ease the function call and reduce redundant code.
Upvotes: 1