PHP Variables: Declaration, Scope, and Data Types

PHP Variables: Declaration, Scope, and Data Types
1. Declaring Variables in PHP
In PHP, variables start with a $ sign.
Variable names are case-sensitive ($name and $Name are different).
Variables do not need explicit type declarations (PHP is loosely typed).
✅ Example:
<?php
$name = "John"; // String
$age = 25; // Integer
$price = 9.99; // Float
$isAdmin = true; // Boolean
?>
<?php
function myFunction() {
$localVar = "I'm local!";
echo $localVar;
}
myFunction();
// echo $localVar; // ❌ Error: Undefined variable
?>
<?php
$globalVar = "I'm global!";
function showVar() {
global $globalVar; // Using 'global' to access outside variable
echo $globalVar;
}
showVar();
?>
<?php
function counter() {
static $count = 0; // Retains value across function calls
$count++;
echo $count . "
";
}
counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3
?>
<?php
$text = "Hello, PHP!";
echo $text;
?>
<?php
$number = 100;
var_dump($number); // Output: int(100)
?>
<?php
$pi = 3.14159;
var_dump($pi); // Output: float(3.14159)
?>
<?php
$isPHPFun = true;
var_dump($isPHPFun); // Output: bool(true)
?>
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Output: Apple
?>
<?php
class Car {
public $brand;
function setBrand($brand) {
$this->brand = $brand;
}
}
$myCar = new Car();
$myCar->setBrand("Toyota");
echo $myCar->brand; // Output: Toyota
?>
🔹 NULL
<?php
$emptyVar = NULL;
var_dump($emptyVar); // Output: NULL
?>
Date: 2025-03-28 00:00:00.000000