phpicoder Nov 1, 2021 php

Hi guys, Today we built-in php variables tutorial, variable is a most important part of php project.

PHP is a Loosely Typed Language, we don't need to disclose the data types of variables. It automatically analyzes the values and converts them to the correct datatype.

PHP variable name starts with the `$` icon and many Rules for PHP variables so read the Rules for PHP

Rules for PHP variables:


PHP variable name starts with the `$` icon
PHP variable name cannot start with a number
PHP variable name must start with a  alpha-numeric characters or the underscore character like (A-z, 0-9, and _ )
PHP variable names are case-sensitive like `$count` and `$COUNT` this is a two different variables

Example:

<?php
  $c = 89;
  $php = 99;
  $java = 75;

  $sum = $c + $php + java;
  $per = $sum/3;

  echo "my percentage is a ".$per;
?>
Output:-
my percentage is a 87.666666

PHP Variables Scope

PHP have a three different variable scopes

  1. local
  2. global
  3. static 

1.local:

Local variable declared under function and can only be accessed under this function has a local scope.

Example:

<?php
function printName() {
  $name = "vikram"; // local variable scope

  echo "my name is a ".$name;
}
printName();

// using $name variable outside the function will generate an error
echo "my name is a ".$name;
?>
Output:-
my name is a vikram
my name is a

2.global:

Global variable declared outside side a function and can only be accessed outside this function has a global scope.

Example:

<?php
$name = "vikram"; // global variable scope

function printName() {
  // using $name variable inside this function will generate an error
  echo "my name is a ".$name;
}
printName();

echo "my name is a ".$name;
?>
Output:-
my name is a 
my name is a vikram

To do this, use the global keyword before this variables accessed inside the function, 

Example:

<?php
$a = 10;
$b = 20;

function printName() {
  global $a, $b;
  $b = $a + $b;
}
printName();

echo $b;
?>
Output:-
30

3.static:

static variable declared and function is a executed after this varable is a deleted.

Example:

<?php
function printNumber() {
  static $a = 0;
  echo $a;
  $a++;
}

printNumber();
printNumber();
printNumber();
?>
Output:-
0
1
2

I hope this tutorial help for you.