开发者

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
$d开发者_C百科om = new MyDocumentHTMLDom();
myFun($dom);

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


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


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


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/


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.


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


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) { ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜