Post-3 (PHP) Declare Variables in PHP - NetwaxUL

Breaking

Facebook Popup

BANNER 728X90

Saturday, March 26, 2016

Post-3 (PHP) Declare Variables in PHP

# Creating (Declaring) Variables in PHP


  • Example: 7

<?php

$txt = "Hi Netwax Lab!";

$x = 5;

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

Output

Hi Netwax Lab!
5
10.5

# How to Output Text and a Variable

  • Example: 8
<?php
$txt = "Hi Netwax Lab!";
echo "Hey $txt!";
?>

Output

Hey Hi Netwax Lab!!

  • Example: 9
<?php
$txt = "Hi Netwax Lab!";
echo "Hey " . $txt . "!"
?>

Output

Hey Hi Netwax Lab!!
  • Example: 10
<?php
$a = 10;
$b = 15;
echo $a+$b;
?>

Output

25

PHP has three different variable scopes:
  1. Local
  2. Global
  3. Static

# Global and Local Scope

Define variable global still not use in inside function
  • Example: 11
<?php
$a = 10; // variable global scope
function First() {
// using a inside this function will generate an error
echo "<p>Variable a inside function is: $a</p>";
}
First();
echo "<p>Variable a outside function is: $a</p>";
?>

Output


  • Example: 12
<?php
function First() {
$a = 10; // variable local scope
// using a outside this function will generate an error
echo "<p>Variable a inside function is: $a</p>";
}
First();
echo "<p>Variable a outside function is: $a</p>";
?>

Output


  • Example: 13
<?php
$a = 10; // variable global scope
function First() {
global $a;
echo "<p>Variable an inside function is: $a</p>";
}
First();
echo "<p>Variable an outside function is: $a</p>";
?>
<?php
$a = 10; // variable global scope
function First() {
global $a;
echo "<p>Variable an inside function is: $a</p>";
}
First();
echo "<p>Variable an outside function is: $a</p>";
?>

Output

Variable an inside function is: 10
Variable an outside function is: 10

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

This array is also accessible from within functions and can be used to update global variables directly.
  • Example: 14
<?php
$a = 10; // variable global scope
function First() {
$GLOBALS['a'] = $GLOBALS['a'] + $GLOBALS['a'];
}
First();
echo "<p>Variable an outside function is: $a</p>";
?>

Output

Variable an outside function is: 20

# Static Keyword

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.
  • Example: 15
<?php
function First() {
static $a = 0;
echo $a.'<br>';
$a++;
}
First();
First();
First();
?>

Output

0
1
2



----

1 comment:

  1. Thanks for this post. I found this very useful. Kanhasoft is a leading CodeIgniter Web Development Company India providing offshore services to foreign countries like USA, UK, Netherland, South Africa, Japan, Denmark, Canada and many more. Visit our site to know more about us.

    ReplyDelete