PHP – function use

As with the previous post about the use method within php (here), you are also able to use the use method attached to a callable function as in

function ($parameter) USE ($somevalue)

So you are able to use any variables that are within scope within the new function, below is an example where I am using the array walk methods callback (which means call a function that is available). The function is using the values within the array ($arrays 4 and 5) and adding them to the $value variable that is passed within the use parameters (here I am using the & symbol which means to pass in reference and not just a copy of the value (you are able to alter the actual parameter passed), so in this instance the $value starts of with 1, then adds 4 and then 5 to it which in turn the result is 10.

$value = 1;
$callback = function ($one) use (&$value) {
	$value += $one;
};
$arrays = array(4,5);
array_walk($arrays, $callback);
print_r("value : " .$value);

And the output would be.

value : 10

PHP – Use

From a follow on from my previous post about namespace, when you want to use another name, shorter than the actual namespace of the namespace you are able to use “use”. Probably best to show in code

include "codingfriends.php";
 
use codingfriends as cf;
 
echo cf\sayHello()."<br/>";

the codingfriends.php file is

<?php
namespace codingfriends;
 
function sayHello()
{
    echo "Say hello from codingfriends.";    
}
 
function sayHelloFromSub()
{
    echo sub\sayHello();
}
?>

so that the “use” will alter the namespace of codingfriends to cf instead so that you are able to call codingfriends as cf, so when

echo cf\sayHello()."<br/>";

is called it will call the codingfriends\sayHello() function.