+ 3
Practical use of Call by Reference in PHP
Is there any practical use of call by reference variable in PHP and if then give an example where it is compulsory to use call by reference.
5 Respostas
+ 1
This is a detailed article.
Hope it helps your problem addressed out.
https://www.elated.com/php-references/
+ 1
Ore Adeleye thanks for the example
No matter how many articles I read about any topic related to programming but having just an example is enough for me to understand it
Again thank you
0
if u really want to change value of variable outside the function
0
It is used to change variable values without creating new variables. For example suppose you want to capitalize all strings in an array.
Inefficient pass-by-value method
<?php
$names = array("dylan", "carlos", "mitch", "fiona");
function capitalize($str){
return ucwords($str);
}
for($i=0; $i < count($names); $i++){
$names[$i] = capitalize($names[$i]);
}
var_dump($names);
?>
Efficient pass-by-reference approach
<?php
$names = array("dylan", "carlos", "mitch", "fiona");
function capitalize(&$str){
$str = ucwords($str);
}
for($i=0; $i < count($names); $i++){
capitalize($names[$i]);
}
var_dump($names);
?>
0
<?php
$x=3;
function square(&$x)
{
$x = $x*$x;
}
echo $x."\n";
square($x);
echo $x."\n";
?>