Variables in PHP are used to store data. A variable always starts with a $ sign followed by the variable name.
<?php
$name = "Samir";
$age = 25;
$price = 199.50;
echo $name;
?>
👉 Explanation:
$ (e.g., $name).Variable scope defines where a variable can be accessed inside a PHP script.
<?php
$globalVar = "I am global";
function testScope() {
$localVar = "I am local";
echo $localVar; // Works
// echo $globalVar; // Error: cannot access global variable directly
}
testScope();
?>
<?php
$x = 10;
$y = 20;
function addNumbers() {
global $x, $y; // Using global keyword
echo $x + $y;
}
addNumbers();
?>
<?php
function counter() {
static $count = 0; // Stays in memory
$count++;
echo $count . "<br>";
}
counter(); // 1
counter(); // 2
counter(); // 3
?>
👉 Explanation:
global keyword or $GLOBALS array.Constants are values that cannot be changed once defined. Unlike variables, constants do not use a $ sign.
<?php
define("SITE_NAME", "MyWebsite");
const VERSION = "1.0";
echo SITE_NAME;
echo VERSION;
?>
👉 Explanation:
define() or const.$ and cannot be changed.