Use variables outside the function

Asked

Viewed 380 times

4

I’m studying php7 and I saw somewhere that it’s now possible to use external function variables, but they’re in the same file. As I recall 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!

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 "outside" variable of the function, regardless of whether it is in the file in question or in an included file.

2

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

$agua = '1 Litro';

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

echo $garrafa();

What is new in PHP 7 that is similar to this are the anonymous classes. They are useful for creating specific classes and will probably not 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;
    }
});

1

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

$message = 'Hello';

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

See working on the Sandbox

Browser other questions tagged

You are not signed in. Login or sign up in order to post.