PHP Variable Outside Function


 

PHP Variable Outside Function

In PHP Functions, a variable can be called either outside the function or inside the function. If we declare a variable within the function, it will not seen outside the function and if you declare a variable outside the function, it will not seen inside the function.

In PHP Functions, a variable can be called either outside the function or inside the function. If we declare a variable within the function, it will not seen outside the function and if you declare a variable outside the function, it will not seen inside the function.

PHP Variable Outside Function

In PHP Functions, a variable can be called either outside the function or inside the function.

If we declare a variable within the function, it will not seen outside the function and if you declare a variable outside the function, it will not seen inside the function.  Let's see the example to understand how it works :

PHP Variable Outside Function Example 1 :

<?php

$text = "I am employee of ROSE INDIA PVT. LTD.!";

function msg()

{

echo $text;

}

msg();

?>

The output of the above example is : Notice: Undefined variable: text in C:\wamp\www\phpVariable\php-variable-outside-function.php on line 5

In the above example, we declared the variable outside the function and asking to print inside the function and when you run this code on your browser, it will show the above output on your screen or browser.

Example 2 :

<?php

function msg()

{

    $text = "I am employee of ROSE INDIA PVT. LTD.!";

}

echo $text;

msg();

?>

The output of the above example is : Notice: Undefined variable: text in C:\wamp\www\phpVariable\php-variable-outside-function.php on line 6.

Here, we declared the variable inside the function and asking to print outside the function and again it will show the above output on your screen, when you will run the code on the browser.

Example 3 :

<?php

function msg()

{

$text = "I am employee of ROSE INDIA PVT. LTD.!";

0

echo $text;

}

msg();

1

?>

The output of the above example is : I am employee of ROSE INDIA PVT. LTD.!

Here, we declared both the variable or echo statement together within the function and it will display the correct output on the browser, when you will run the code on your browser.

2

This is only one way to display the outside variable inside the function is to use global variable. By declaring global variable inside the function, that means it all references to either variable will refer to the global version.

<?php

$num1 = "5";

3

$num2 = "6";

function multi()

{

4

global $num1,$num2;

$num2 = $num1*$num2;

}

5

multi();

echo $num2;

?>

6

The output of the above example is : 30

 

Ads