frame

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In Register

PHP Variables

PHP Variables

Create different variables

<!DOCTYPE html>
<html>
<body>

<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;

echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>

</body>
</html>


Test global scope (variable outside function)

<!DOCTYPE html>
<html>
<body>


<?php
$x = 5; // global scope
 
function myTest() {
  // using x inside this function will generate an error
  echo "<p>Variable x inside function is: $x</p>";
} 
myTest();


echo "<p>Variable x outside function is: $x</p>";
?>


</body>
</html>

Test local scope (variable inside function)

<!DOCTYPE html>
<html>
<body>


<?php
function myTest() {
  $x = 5; // local scope
  echo "<p>Variable x inside function is: $x</p>";
} 
myTest();


// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>


</body>
</html>


Use the global keyword to access a global variable from within a function

<!DOCTYPE html>
<html>
<body>


<?php
$x = 5;
$y = 10;


function myTest() {
  global $x, $y;
  $y = $x + $y;
} 


myTest();  // run function
echo $y; // output the new value for variable $y
?>


</body>
</html>

Use the $GLOBALS[] array to access a global variable from within a function

<!DOCTYPE html>
<html>
<body>


<?php
$x = 5;
$y = 10;


function myTest() {
  $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
} 


myTest();
echo $y;
?>

</body>
</html>

Use the static keyword to let a local variable not be deleted after execution of function

<!DOCTYPE html>
<html>
<body>

<?php
function myTest() {
 static $x = 0;
 echo $x;
 $x++;
}

myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?> 

</body>
</html>
Tagged:
Sign In or Register to comment.

Developer

| make vanilla clean and light
@ 2016 Your Sitename, All rights reserved. Material Design is a design language developed by Google. Material Design makes more liberal use of grid-based layouts and responsive animations and transitions.
Powered by VanillaForums, Designed by ThemeSteam

Contact us

info@example.com
support@example.com
(800) 3032120

Get In Touch