has how to use php variable within functions

1

My question is, can I use a variable that was defined outside a function within a function? if I create a phone variable to receive data via form and declare it, can I use that same variable with this value that was entered into the form within my function?

    
asked by anonymous 20.10.2017 / 04:26

2 answers

2

To answer your question, you first need to understand what is variable scope .

  

The scope of a variable is the context where it was defined. In PHP most of the variables have only local scope.

Scope types in PHP:

  • local : The scope of a variable is the context where it was defined. Most PHP variables have only local scope. This local scope includes the included and required files.
  • global : declared out of any function and accessed from any place (within functions using "global $ var")
  • static : equals the local variable, but retains its value after the function terminates.
  • parameter - Same as local variable, but with its past values as arguments to the function.

Local scope example:

<?php
$a = 10; // local
echo $a;

Global Scope Example:

<?php
$a = 5; // Global

function minhaFuncao() {
    global $a;
    echo $a; // Global
}

minhaFuncao();

Note: global variaties can be accessed within functions by adding the variable's left to the global keyword. Once outside the function just enter the name of the variable (ex: $ var)

Example passing a local variable as a parameter to the function:

<?php
$a = 5; // local

function minhaFuncao($a) {
    echo $a; // local, aqui é outra variável diferente
}

minhaFuncao($a);

Note: In% w / w I could give any name to the variable, since it only exists in the local scope of the function.

For more information and examples for the other scopes consult the official documentation: link

p>     
20.10.2017 / 04:58
0

Most PHP variables have only local scope.

If you want to use a variable defined outside a function, the easiest way is to pass it via parameter, as in the example below:

$a = 'ola!';

function teste($parametro) {
 echo $parametro;
}

teste($a);

Print on screen:

ola!
    
20.10.2017 / 04:55