Home Tutorial Php PHP Variable Outside Function

 
 

Share on Google+Share on Google+
PHP Variable Outside Function
Posted on: January 14, 2010 at 12:00 AM
Advertisement
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.!";

echo $text;

}

msg();

?>

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.

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";

$num2 = "6";

function multi()

{

global $num1,$num2;

$num2 = $num1*$num2;

}

multi();

echo $num2;

?>

The output of the above example is : 30

 

Advertisement

Related Tags for PHP Variable Outside Function:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 14, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com