Ben
Ben

Reputation: 25807

Are php5 function parameters passed as references or as copies?

Are Php function parameters passed as references to object or as copy of object?

It's very clear in C++ but in Php5 I don't know.

Example:

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

Is parameter $dom passed as a reference or as a copy?

Upvotes: 4

Views: 854

Answers (6)

newacct
newacct

Reputation: 122459

It has nothing to do with function parameters. PHP 5 only has pointers to objects; it does not have "objects" as values. So your code is equivalent to this in C++:

MyDocumentHTMLDom *dom = new MyDocumentHTMLDom;
myFun(dom);

Now, many people mentioned pass by value or pass by reference. You didn't ask about this in the question, but since people mention it, I will talk about it. Like in C++ (since you mentioned you know C++), pass by value or pass by reference is determined by how the function is declared.

A parameter is pass by reference if and only if it has a & in the function declaration:

function myFun(&$dom) { ... }

just like in C++:

void myFun(MyDocumentHTMLDom *&dom) { ... }

If it does not, then it is pass by value:

function myFun($dom) { ... }

just like in C++:

void myFun(MyDocumentHTMLDom *dom) { ... }

Upvotes: 0

Tomasz Struczyński
Tomasz Struczyński

Reputation: 3303

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

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

Upvotes: 9

Ris90
Ris90

Reputation: 841

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

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 73001

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.

Upvotes: 1

user382074
user382074

Reputation:

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/

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212442

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

Upvotes: 1

Related Questions