can use variable php within the functions

Asked

Viewed 70 times

1

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

2 answers

2


To answer your question you must first understand what is scope of variables.

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

Scope types in PHP:

  • local: the scope of a variable is the context in which it was defined. Most PHP variables have only local scope. This local scope includes the included and required archives.
  • global: declared outside any function and accessed from any place (within functions using "global $var")
  • Static: same as the local variable, but keeps its value after the function is closed.
  • Parameter - Same as the local variable, but with its past values as arguments to the function.

Example of local scope:

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

Example of global scope:

<?php
$a = 5; // Global

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

minhaFuncao();

Note: global variaties can be accessed inside functions by adding the left of the variable to the word global. Already outside the function just enter the variable name (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);

Obs: on minhaFuncao($a) I could give any name to the variable, because it only exists in the local scope of the function.

For more information and examples for the other scopes see the official documentation: http://php.net/manual/en/language.variables.scope.php

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);

Will print on screen:

ola!

Browser other questions tagged

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