views:

63

answers:

5

Hi,

Does php function parameters pass as ponter to object or as copy of object?

Its very clear in C++ but in php5 I don't know.

Example:

<?php
$dom=new MyDocumentHTMLDom();
myFun($dom);
?>

parameter $dom pass as pointer or as copy?

Thanks

A: 

Copy, unless you specify, in your case, &$dom in your function declaration.

UPDATE

In the OP, the example was an object. My answer was general and brief. Tomasz Struczyński provided an excellent, more detailed answer.

Jason McCreary
I think this is not exactly true, if the parameter is object.
Tomasz Struczyński
My mistake. I was speaking more generally. In this case the OP example was indeed an object.
Jason McCreary
+2  A: 

Objects are always pass by reference, so any modifications made to the object in your function are reflected in the original

Scalars are pass by reference. However, if you modify the scalar variable in your code, then PHP will take a local copy and modify that... unless you explicitly used the & to indicate pass by reference in the function definition, in which case modification is to the original

Mark Baker
+2  A: 

In PHP5, the default for objects is to pass by reference.

Here is one blog post that highlights this: http://mjtsai.com/blog/2004/07/15/php-5-object-references/

That's incorrect. It passes a *copy* of an object identifier. This creates a *new* zval struct in the internal symbol table. Passing by reference in PHP uses the *same* zval struct, but increments the refcounts and marks it as a reference.
Daniel Egeberg
+8  A: 

In PHP5, objects are passed by reference. Well, not exactly in technical way, because it's a copy; but object variables are in PHP5 storing object IDENTIFIER, not the object itself, so essentially it's same as passing by reference.

More here: http://www.php.net/manual/en/language.oop5.references.php

Tomasz Struczyński
Thank you Tomasz
Yosef
+1  A: 

in php5 objects pass by reference, in php4 and older - by value(copy) to pass by reference in php4 you must set & before object's name

Ris90