PHP Variable Scope Part 004

Publicado em: 01 Janeiro 1970
no canal de: TUTORIAL
238
9

PHP Variable Scope Part 004

PHP Variable Scope
In PHP, variables can be written anywhere in the script.

PHP has three different variable scopes:
1-global
2-local
3-static

/*

Notes:
For the larger and smaller squares I have changed it to *
because that character is not allowed in the Youtube description

1.Variables declared outside the function have GLOBAL SCOPE
and can only be accessed outside the function
*/
echo "--------------Global variable example ------"


example
*?php
$x = 125; // global scope

function robertusnews() {
// using x inside this function will generate an error
echo "*p*Variable x inside function is: $x*/p*";
}
robertusnews();

echo "*p*Variable x outside function is: $x*/p*";
?*

The global keyword is used to access global variables from within a function.
To do this, use the global keyword before the variable (inside the function):


*?php
echo "------ global variable example in function ---";
$x = 5;
$y = 20;

function robertusnews() {
global $x, $y;
$y = $x + $y;
}

robertusnews(); // run function
echo "*br*";
echo $y; // output the new value for variable $y
?*

?*



2// Variables declared in a function have a LOCAL SCOPE and can only be accessed within that function:
example
*?php
function robertusnews() {
$x = 150; // local scope
echo "*p*Variable x inside function is: $x*/p*";
}
robertusnews();

// using x outside the function will generate an error
echo "*p*Variable x outside function is: $x*/p*";
?*


3. static (the use of this static variable is so that local variables that have been created are not deleted)
when a function finishes/executes, all its variables will be cleared. However, sometimes we want
local variables are NOT deleted. We need it for further work. so that every time
the function is called, that variable will still have the information it contained since the last time
function is called. To do this, use static as the keyword when you first declare a variable:

*?php
function robertusnews() {
static $x = 0;
echo $x;
$x++;
}

robertusnews();
echo "*br*";
robertusnews();
echo "*br*";
robertusnews();
?*


Social Media :
Youtube :    / robertusnews  
Wordpress : https://robertusnewss.blogspot.com/
Blog : https://robertusnewss.blogspot.com/
Twitter :   / robertusnews  
Instagram :   / robertusnews  

-------------------------------------------------- -------
Contact : robertusnews@gmail.com
-------------------------------------------------- -------


Nesta página do site você pode assistir ao vídeo on-line PHP Variable Scope Part 004 duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário TUTORIAL 01 Janeiro 1970, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 238 vezes e gostou 9 espectadores. Boa visualização!