"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Why would you want to? function results are not static - for each request they would get rerun, thus slowing down the performance of the system. if you can guarantee that it will only reference one element, then it should be fine to do.
Also, you could use a wrapper class to do this, rather than what is being proposed.
It just means you can get the value of an element part way through an array without setting an intermediate variable. Obviously though if you need more than one value from that array it would unnecesarilly raise the workload.
True that my function could return a FALSE element and give misleading results. However using the above code does not give an error if the required index does not exist, which might be what you want but is different behaviour from normal array referencing. Using this function:
Code:
function arrayElement($arr, $index)
{
return $arr[$index];
}
accurately emulates the referencing of the array (or seems to) ie it will reference the element if it's there, otherwise kick off an error. And it circumvents the necessity of setting a variable for the array.
Naturally, if you're going to be referencing more than 1 element in the array you would set it to a variable. You pick that up pretty early in java type stuff.
function arrayElement($arr, $index) {
return $arr[$index];
}
... PHP does create an array, even if only temporarily. From a memory or CPU standpoint, there's no advantage there. I understand the issue of not wanting to use a $variable name for the results of a function. But is it worth the overhead?
When I referred to "overhead", I not only meant performance but human overhead, as well.
When you start using functions over functions to "hide" something, in this case an array, you don't necessarily contribute to that cleanness. As long as you're writing code for personal use, all is fine. But if an error pops up and your code is visited by another programmer, it may become an issue.
Of course, I realize, it's all in the definition of "cleanness".
Bookmarks