M. Sokolewicz wrote:
Philip Thompson wrote:
On 10/19/07, Stut <stuttle@xxxxxxxxx> wrote:
Ondra Zizka wrote:
Hello,
please look at the code bellow and tell if it does not conform to rules
of
returning a reference from a function.
In the first method, I return reference to $sRet variable, and PHP is
quiet.
But in the second, PHP says:
Notice: Only variable references should be returned by reference in
C:\web\php_bug_reference_return.php on line 8 // return $ref =&
$this->ReturnReference();
(Note that the notice does not concern the first method as the notice
appears even if I remove references from the first method.)
But I am still just returning a reference to a variable, so I guess
it's
actually correct, isn't it?
Thanks for oppinions.
Ondra Zizka
<?php
class A {
function &ReturnReference(){
$sFoo = "Hi.";
return $sRet =& $sFoo;
}
function &RequireReference(){
return $ref =& $this->ReturnReference();
}
}
$oA = new A();
$ref = $oA->RequireReference();
?>
When you define a function as returning a reference (with the & prefix)
you do not need to get the reference yourself, PHP will do it for you.
The following should work fine...
<?php
class A
{
function & ReturnReference()
{
$sFoo = "Hi.";
return $sFoo;
}
function & RequireReference()
{
$retval = $this->ReturnReference();
return $retval;
}
}
$oA = new A();
$ref = $oA->RequireReference();
?>
-Stut
I know we went over references (C) in first semester programming.
Excuse me
if this is too trivial, but why would you want to use a reference? I
thought
in PHP, specifically, that it is unnecessary to use references.
A lil' embarrassed,
~Philip
in PHP4 it was occasionally a good idea to use references when assigning
objects. As of PHP5 the reasons to use references have been reduced to
virtually none. As the manual states "if you think you need to use
references, think again, you probably don't."
Say you have a function that builds a fairly large array and then
returns it. If you just return it as usual PHP will make a copy of that
array and therefore use twice the amount of memory than it needs to.
References also provide a way to return more than one variable from a
function, but I doubt many PHP developers come across the need to do that.
Where in the manual does it say that? I've never seen it and I can't
find it.
-Stut
--
http://stut.net/
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php