Friday, 1 September 2017

PHP | Simple PHP Variables Scope in Program - W3Tricks

PHP Variables Scope in Program


Variables Scope

  • Variables can be declared anywhere in the PHP program.
  • Main Two Type of variable scopes
  • 1. Global. 2. Local.

What is Global variable scopes?

  • A variable declared outside of any function and block has a GLOBAL SCOPE and can only be accessed outside a function and block.

What is Local variable scopes?

  • A variable declared within any function and block has a LOCAL SCOPE and can only be accessed within that function and block.

Program

<?php

$data = 5; // Global Variable.

function info(){
$data = 10; // Local Variable.
echo "IT IS Local Variable". $data . "<br/>";
}
info();
echo "<br />IT IS Global Variable". $data;

?>

Global keyword

  • Use Global keyword in Program and what is a use of global function?
  • The global keyword is used to access a global variable from within a function and block.

Program

<?php

$A = 5; // Global Variable.

function info(){
$B = 10; // Local Variable.
global $A;
$sum = $A + $B;
echo "Output Sum :". $sum . "<br/>";
}
info();

?>

Output


0 comments:

Post a Comment