Thursday, 31 August 2017

What does the "&" sign mean in PHP?




I was trying to find this answer on Google, but I guess the symbol & works as some operator, or is just not generally a searchable term for any reason.. anyhow. I saw this code snippet while learning how to create WordPress plugins, so I just need to know what the & means when it precedes a variable that holds a class object.



//Actions and Filters
if (isset($dl_pluginSeries)) {

//Actions
add_action('wp_head', array(&$dl_pluginSeries, 'addHeaderCode'), 1);

//Filters
add_filter('the_content', array(&$dl_pluginSeries, 'addContent'));
}

Answer



This will force the variable to be passed by reference. Normally, a hard copy would be created for simple types. This can come handy for large strings (performance gain) or if you want to manipulate the variable without using the return statement, eg:



$a = 1;

function inc(&$input)

{
$input++;
}

inc($a);

echo $a; // 2


Objects will be passed by reference automatically.




If you like to handle a copy over to a function, use



clone $object;


Then, the original object is not altered, eg:



$a = new Obj;
$a->prop = 1;

$b = clone $a;
$b->prop = 2; // $a->prop remains at 1

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...