views:

66

answers:

2

Update: in

http://php.net/manual/en/language.oop5.references.php

it says:

One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true.

Why is that? The following is a reason which I don't know is completely true or not:

I think loosely speaking, foo can be said to be an object, or an instance of the class Foo.

But is it true that very technically speaking, foo is just a reference, the exactly same way in Java and in Ruby, where variable foo is always just a reference to an object.

So that's why in PHP,

function add($obj) {
  $obj->a++;
}

We don't say "pass by reference", but very technically speaking, we are passing a value, which is a reference. So, it is "passing the reference", not "passing by reference".

But, if we say in PHP, that foo is an object, then I guess "passing by reference" can make sense. So is it true? foo is said to be a reference to an object, not an object, so that's why we are just "passing by value"?

A: 

All objects are per default passed by reference in PHP 5+, before PHP 5 to pass by reference you used the "&" operator

Meaning that if you pass a object into a method the reference is copied, and another variable inside the method will contain a copy of the reference.

So you are not passing reference's by reference per default :), so you cant assign the variable containing the copy of the reference a new value and affect the original reference.

madsleejensen
it is because in the formal PHP docs: http://php.net/manual/en/language.oop5.references.php saysOne of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true.
動靜能量
What you describe in your answer in not pass-by-reference but pass-by-value of a reference.
Vincent Robert
A: 

$foo is not an object, it is a reference. Saying that $foo is an object is an error, $foo is a reference that points to an object.

References are passed by value, like any other arguments in PHP (Java and Ruby also), so you cannot directly assign the reference to modify it, but you can work however you want on the object it points.

In order to simplify the abstraction, programmers sometimes say that "$foo is an object", this is wrong but it is easier than saying the whole "$foo is a reference that points to an object". In many cases, the difference does not actually matter except in some edge cases.

Vincent Robert
so I guess http://php.net/manual/en/function.is-object.php is_object — Finds whether a variable is an object -- it really means "whether a variable is a reference to an object."
動靜能量
Yup. Never said PHP documentation was consistent :)
Vincent Robert