Laravel
504
w3alert.com
20-12-2019
PHP variable a name of memory location that save or holds information or value or data like strings, arrays, numeric value, objects, characters, etc. The PHP variable is a temporary storage that is used to store data temporarily. In PHP, basic variable is declared using "$"" sign followed by variable name.
You can see the below, how to declare or create variable in PHP.
<?php $name = 'string'; // string varible $a = 5; // int type variable ?>
PHP is a loosely typed language, that means PHP automatically converts the variable to its correct data type.
The PHP variables can be declared or created anywhere in the code or script. There are three different variable scopes in PHP. See below:
A local scope is a restricted range of variables within which a code block is declared. That block can be a function, class, or any conditional period. Variables within this limited local scope are known as local variables of that specific code block.
<?php $abc = 'Hello Word'; //explain local variables scope function localValFunction() { // This $abc is local to this function $abc = 'hello developers'; echo "$abc \n"; } localValFunction(); // $abc outside function localValFunction() is a echo "Variable abc outside localValFunction() is $abc \n"; ?>
As its name, the global field provides wide access to variables declared in this scope. Variables in the global scope can be accessed from outside a function or class independent of its range.
<?php $abc = 20; //explain global variables scope function globalValFunction() { // the variable $abc to access within global $abc; echo "Variable abc inside function : $abc \n"; } globalValFunction(); echo "Variable abc outside function : $abc \n"; ?>
It is a feature of PHP to remove variables, it completes its execution and memory is freed. But sometimes we need to store the variable even after the completion of the function execution. To do this we use the static keyword and the variable is then called a static variable.
<?php //explain static variables scope function staticValFunction() { // static variable static $num = 76; $sum = 88; $sum++; $num++; echo $num, "\n"; echo $sum, "\n"; } // first function call staticValFunction(); // second function call staticValFunction(); ?>