Are php5 function parameters passed as links or as copies?

Are the parameters of the Php function passed as object references or as a copy of an object?

This is very clear in C ++, but in Php5 I do not know.

Example:

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

Is $dom as a link or as a copy?

+4
source share
6 answers

In PHP5, objects are passed by reference . Well, not quite technically, because it's a copy, but object variables in PHP5 store the IDENTIFIER object, not the object itself, so it’s essentially the same as passing by reference.

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

+9
source

Copy if you did not specify &$dom in the function declaration in your case.

UPDATE

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

+1
source

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

Scalara follow the link. However, if you change the scalar variable in your code, then PHP will take a local copy and change it ... if you have not explicitly used or specified a pass by reference in the function definition, in which case the modification refers to the original

+1
source

In PHP5, by default, objects are passed by reference.

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

+1
source

in php5 objects are transferred by reference, in php4 and later - by value (copy) to pass by reference in php4 you must set & in front of the name of the object

0
source

It has nothing to do with function parameters. PHP 5 has only 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 of the people mentioned go by value or follow the link. You did not ask about this in the question, but since people mention it, I will talk about it. As in C ++ (since you mentioned that you know C ++), passing a value or passing by reference is determined by how the function is declared.

A parameter is passed by reference if and only if the function declaration contains & :

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

as in C ++:

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

If this is not the case, then this is a pass by value:

 function myFun($dom) { ... } 

as in C ++:

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

Source: https://habr.com/ru/post/1314545/


All Articles