PHP: Variables

By Xah Lee. Date: . Last updated: .

Global and Local variables

(Unlike perl, the dollar sign does not change depending on the value of the variable. In PHP, there is no perl's concept of Context.)

<?php
$xx = 4;
echo $xx;
?>

Basically all variables are global.

Variables Inside Function

Variables inside functions definition are local to that function.

<?php
$x = 4;

function ff()
{
  echo "value of x is $x";
  # x is null
  # Warning: Undefined variable $x
}

ff();
# value of x is
?>

Inside Function, refer to global variable

To refer to global vars inside function definition, declare it first by putting global in front of the var.

<?php
$x = 4;

function ff()
{
    global $x;
    echo "x is $x";
}

ff();
# x is 4
?>

Curly brace block does not make variable local

<?php

$x = 4;

{
# Curly brace block does not make variable local
$x = 3;
}

echo $x;
# 3

?>