I'm fairly new to PHP; most of my programming experience so far has been in C++. So, naturally, I get concerned about efficiency. In C++ you never ever ever return an object or an array at the end of a function, but if you need the data, you just return a pointer.
So my question is: is it bad for efficiency to be using arrays as return values, or does PHP just use a pointer in the background and just not show me for convenience?
PHP returns a reference if it's optimal for the interpreter to do so. Normally parameters passed to functions are copied, though you pass a parameter by reference and therefore get a return value by reference like so:
function blah(&$foo) {
$foo = array();//or whatever
//note no return statement
}
//elsewhere
$x = "whatever";
blah($x);
//$x is now an array.
Because of &
, $foo
is treated as a reference, and so modifications to that variable are treated as modifications to the reference.
Or you can force the function to return a reference:
function &blah() {
//some stuff
return $foo;//goes back as a reference
}
This latter shouldn't, according to the docs, be done unless you have a non-optimization reason to do so.
That said, PHP isn't terribly efficient, and worrying about these things is generally premature - unless you're seeing an actual performance bottleneck in your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With