|
Posted by Jerry Stuckle on 05/07/07 14:02
Vince Morgan wrote:
> "Jerry Stuckle" <jstucklex@attglobal.net> wrote in message
> news:xMGdnWvEq_C8eKDbnZ2dnUVZ_uqvnZ2d@comcast.com...
>> Vince Morgan wrote:
>>> I guess I don't understand how references work in php;
>>> Calling a class member function below as an example;
>>> function &getRow()
>>> {
>>> return odbc_fetch_array($this->_det);
>>> }
>>> I would expect that I should end up with nothing as there is nothing to
>>> actualy reference.
>> But you do have something to reference. odbc_fetch_array returns an
>> array, and you are returning a reference to that array.
>>
>
> If it passing an array to $var then it isn't behaving as a reference, at
> least not as I understand it. It would be behaving as though I had
> requested passing the array itself in the call wouldn't it?
>
You do not "pass" anything to a variable. You pass things to functions,
but you *assign* things to an array.
All you are doing in your getRow() is returning a reference to the array
returned by ordb_fetch_array. It is really no different than:
function &getRow() {
$x = odbc_fetch_array($this->_det);
return $x;
}
You just left out the middle step, which is perfectly legitimate.
And once you get back, it is assigning that reference to the array to
$var.
>> No surprise at all. It should work that way.
>
> Why is that?
>
>> It won't in C++ or Java if odbc_fetch_array returns a reference.
>
> I would have thought that the '&' modifier would do the same in php too
> Jerry.
>
You really should watch what you quote. The entire quote was:
>> In other languages I have more experience with this would throw an
>> error, or leave you with a reference to nothing, however in php 5 I
>> can use this variable hereon without a problem.
>It won't in C++ or Java if odbc_fetch_array returns a reference. It
>will work just fine.
And it won't cause an error in C++ or Java because it's perfectly valid
code. In either case you're returning a reference.
>> All a variable is is a place to keep something to use later. You don't
>> need to use it again in this function, so there's no need to create a
>> variable. Just return the array directly, as is being done.
>
> Yes, it is assigning an array evidently, rather than a reference to an array
> so that would mean that the request for a reference it being ignored here?
>
> Regards,
> Vince
>
>
What do you expect to be different? Operations on a reference are
exactly the same as operations on a copy. The *only* difference in your
code is that if you change a reference, you change the original. if you
change a copy, you do not.
And if you're just accessing (and not changing) the any values, you have
no way of telling if you're acting on a copy or a reference, unless you
go back to see how it was passed or returned.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================
Navigation:
[Reply to this message]
|