开发者

what does & do in php

I have this code

$myNew开发者_如何转开发Class->cars =& Orders_Car::GetRecords($myNewClass->searchString);
                   ^

what is & doing there. thanks


It creates a reference. If you don't know what a reference is, read this : http://www.php.net/manual/en/language.references.php


It changes the variable to be 'passed by reference'. This is as opposed to passing a copy of the variable in.

See the manual for details.

One common use is in foreach.

Typically, foreach operates on a copy of the iterable array or object.

That means

$salad=array(1,2,3);
foreach ($salad as $leaf){
  $leaf+=1;
  }
echo $salad[0];// output: 1   

foreach ($salad as &$leaf){
  $leaf+=1;
  }
echo $salad[0];// output: 2 because & made the assignment affect the original array


Read Do not use PHP references by PHP expert Johannes Schlüter

PHP references are a holdover from PHP 4, where objects were passed by value instead of by reference unless you deliberately made them by reference. This isn't necessary when using PHP 5, because all objects are passed by reference in PHP 5 all the time.

Scalars and arrays are still passed by value by default in PHP 5. If you need to pass them by reference, you should just use an object.


It is used for passing values by reference rather than by value which is default in php.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜