Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP &$string - What does this mean? [duplicate]

Tags:

php

operands

I've been googling but I can't find anything.

$x->func(&$string, $str1=false, $str2=false); 

what does that & before $string &$string do?

like image 382
Mickey Avatar asked Dec 06 '13 08:12

Mickey


People also ask

What is PHP is used for?

PHP (Hypertext Preprocessor) is known as a general-purpose scripting language that can be used to develop dynamic and interactive websites. It was among the first server-side languages that could be embedded into HTML, making it easier to add functionality to web pages without needing to call external files for data.

What coding is PHP?

PHP is a server side scripting language. that is used to develop Static websites or Dynamic websites or Web applications. PHP stands for Hypertext Pre-processor, that earlier stood for Personal Home Pages. PHP scripts can only be interpreted on a server that has PHP installed.


2 Answers

You are assigning that array value by reference.

passing argument through reference (&$) and by $ is that when you pass argument through reference you work on original variable, means if you change it inside your function it's going to be changed outside of it as well, if you pass argument as a copy, function creates copy instance of this variable, and work on this copy, so if you change it in the function it won't be changed outside of it

Ref: http://www.php.net/manual/en/language.references.pass.php

like image 93
Krish R Avatar answered Sep 29 '22 11:09

Krish R


The & states that a reference to the variable should be passed into the function rather than a clone of it.

In this situation, if the function changes the value of the parameter, then the value of the variable passed in will also change.

However, you should bear in mind the following for PHP 5:

  • Call time reference (as you have shown in your example) is deprecated as of 5.3
  • Passing by reference when specified on the function signature is not deprecated, but is no longer necessary for objects as all objects are now passed by reference.

You can find more information here: http://www.php.net/manual/en/language.references.pass.php

And there's a lot of information here: Reference — What does this symbol mean in PHP?

An example of the behaviours of strings:

function changeString( &$sTest1, $sTest2, $sTest3 ) {     $sTest1 = 'changed';     $sTest2 = 'changed';     $sTest3 = 'changed'; }  $sOuterTest1 = 'original'; $sOuterTest2 = 'original'; $sOuterTest3 = 'original';  changeString( $sOuterTest1, $sOuterTest2, &$sOuterTest3 );  echo( "sOuterTest1 is $sOuterTest1\r\n" ); echo( "sOuterTest2 is $sOuterTest2\r\n" ); echo( "sOuterTest3 is $sOuterTest3\r\n" ); 

Outputs:

C:\test>php test.php  sOuterTest1 is changed sOuterTest2 is original sOuterTest3 is changed 
like image 20
Rob Baillie Avatar answered Sep 29 '22 11:09

Rob Baillie