Creating (Declaring) PHP Variables
In PHP, a variable starts with the
$ sign, followed by the name of the variable:Example 1:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
Output Variables
The PHP
echo statement is often used to output data to the screen.The following example will show how to output text and a variable:
Example 1:
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
$txt = "W3Schools.com";
echo "I love $txt!";
?>
Example 2:
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
Example 3:
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
Example 4:
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>PHP The global Keyword
The
global keyword is used to access a global variable from within a function.To do this, use the
global keyword before the variables (inside the function):Example 1:
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15?>Example 2:
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15?>PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the
static keyword when you first declare the variable:Example 1:
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Comments
Post a Comment