Unit 1 (4th)
Unit 1 (4th)
(4 One)
th
• <html>
• <body>
• <?php
• $txt = "Hello world!";
• $x = 5;
• $y = 10.5;
• echo $txt;
• echo "<br>";
• echo $x;
• echo "<br>";
• echo $y;
• ?>
• </body>
• </html>
Example
• <html>
• <body>
• <?php
• $x = 5;
• $y = 4;
• echo $x + $y;
• ?>
• </body>
• </html>
PHP variable naming conventions
• Variable start with a $ sign.
• Variable name only start with a letter and underscore.
(_) i.e. the variable name should be alphanumeric.
• It cannot start with a number.
• It is a case sensitive which implies that the variable num
in lower case is different from variable NUM in upper
case.
• Don’t use predefined constant name. Eg. PHP_VERSION,
PHP_OS etc.
• Don’t use keyword.
Types of Variables –.
• there are 04 types of variables
• Local Variable – the variable which is declared inside a function has a local scope. Its value
remains valid just with in the function.
• <html>
• <body>
• <?php
• function myTest() {
• $x = 5; // local scope
• echo "<p>Variable x inside function is: $x</p>";
• }
• myTest();
• </body>
• </html>
Global Scope (variable) Keyword –
• <?php
• $x = 5;
• $y = 10;
• function myTest() {
• global $x, $y;
• $y = $x + $y;
• }
• </body>
• </html>
Static Variable
• 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 we
first declare the variable:
Example
• <html>
• <body>
• <?php
• function myTest() {
• static $x = 0;
• echo $x;
• $x++;
• }
• myTest();
• echo "<br>";
• myTest();
• echo "<br>";
• myTest();
• ?>
• </body>
• </html>
SuperGlobal Variable
• Super global are built in variable that are always
available in all scopes.
• It can be accessed them from any function, class or file
without using global keyword.
• PHP super global variable is used to connect PHP with
HTML forms. Some super global variables are –
• $_GLOBAL $_GET $_SESSION
• $_SERVER $_FILES $_COOKIE
• $_REQUEST $_ENV
• $_POST $_COOKIES
• Note : these are always written in upper case letter.
Example
• <html>
• <body>
• <?php
• $a=10;
• $b=20;
• function disp()
• {
• Echo $GLOBALS['a']."<br>";
• Echo $GLOBALS['b']."<br>";
• $GLOBALS['z'] = $GLOBALS['a'] + $GLOBALS['b'];
•
• }
• disp();
• //echo $a."<br>";
• echo "The Sum is = ".$z;
• ?>
• </body>
• </html>