Saturday, 24 April 2021

Php: Access variables defined outside of a function

There are two ways to access the variables defined outside of a function.

a.   Using global keyword

b.   Using $GLOBALS array

 

Using global keyword

 

Syntax

global $variable_name;

 

Use the keyword ‘global’ followed by variable name to access the variable defined outside of a function.

 

Example

$name = 'Krishna';

$age = 32;

$msg = 'Hello';

 

global_variable_demo.php

#!/usr/bin/php

<?php
   function welcome_me(){
        global $name;
        global $age;
        global $msg;

        $msg = $msg . ' ' . $name . ', ' . 'you are ' . $age . ' years old';
   }

   $name = 'Krishna';
   $age = 32;
   $msg = 'Hello';

   welcome_me();
   echo $msg;

?>

Output

$./global_variable_demo.php 

Hello Krishna, you are 32 years old


Using $GLOBALS array

 

Syntax

$GLOBALS['variable_name']

 

Example

$my_name =  $GLOBALS['name'];

$my_age =  $GLOBALS['age'];

$my_msg =  $GLOBALS['msg'];

 

Find the below working application.

 

globals_array_demo.php

#!/usr/bin/php

<?php
   function welcome_me(){
        $my_name =  $GLOBALS['name'];
        $my_age =  $GLOBALS['age'];
        $my_msg =  $GLOBALS['msg'];

        $GLOBALS['msg'] = $my_msg . ' ' . $my_name . ', ' . 'you are ' . $my_age . ' years old';
   }

   $name = 'Krishna';
   $age = 32;
   $msg = 'Hello';

   welcome_me();
   echo $msg;

?>


Output

$./globals_array_demo.php 

Hello Krishna, you are 32 years old







 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment