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
-------------------------------------------------- -------
In questa pagina del sito puoi guardare il video online PHP Variable Scope Part 004 della durata di ore minuti seconda in buona qualità , che l'utente ha caricato TUTORIAL 01 gennaio 1970, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 238 volte e gli è piaciuto 9 spettatori. Buona visione!