Use out-of-function variables

4

I'm studying php7 and I've seen somewhere that it's now possible to use external function variables, but they're in the same file. From what I remember it was something like this:

<?php 
$agua = '1 Litro';

function listaDeCoisas($item1,$item2) use $agua{
   return 'Lista: '.$item1.','.$item2.', Agua: '. $agua;
}

I want to know if this is really possible and how to use it!

    
asked by anonymous 26.12.2016 / 22:36

3 answers

6

This was already possible in older versions. You can use the scope global .

Example:

$msg = "Olá!";

function exibeMsg()
{
    global $msg;
    echo $msg;
}

exibeMsg(); // Imprimirá "Olá!"

You can access the variable "outside" the function, regardless of whether it is in the file in question or in an included file.

    
26.12.2016 / 23:03
2

I think you want to do this with anonymous functions. Also known as clousures , they are available from PHP 5.3 :

$agua = '1 Litro';

$garraga = function ($item1,$item2) use ($agua) {
   return 'Lista: '.$item1.','.$item2.', Agua: '. $agua;
}

echo $garrafa();

What went back in PHP 7 which looks like this are the anonymous classes . They are useful for creating specific classes and are unlikely to be reused.

// PHP 5
class Logger
{
    public function log($msg)
    {
        echo $msg;
    }
}

$util->setLogger(new Logger());

// Opção no PHP 7+ 
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});
    
26.12.2016 / 23:27
1

The keyword use is only allowed in anonymous functions or clousures as in the example below;

$message = 'Hello';

$example = function () use ($message) {
    var_dump($message);
};
$example();

See it working in the Sandbox

    
26.12.2016 / 23:28