Lesson 3 of 20

Variables & Data Types

Variables and Types

PHP variables start with a $ sign. PHP is dynamically typed — variables don't need type declarations.

Example
<?php
// Variables (start with $)
$name = "Alice";        // string
$age = 25;              // integer
$price = 9.99;          // float
$isActive = true;       // boolean
$nothing = null;        // null

// Check type
echo gettype($name);    // "string"
echo is_string($name);  // true
echo is_int($age);      // true

// Type casting
$str = "42";
$num = (int) $str;      // 42
$float = (float) "3.14"; // 3.14
$bool = (bool) 1;       // true

// Constants
define("TAX_RATE", 0.08);
const MAX_USERS = 100;
echo TAX_RATE;  // 0.08
?>

Variable Scope

PHP has global, local, and static variable scope. Functions have their own scope by default.

Example
<?php
$globalVar = "I'm global";

function test() {
    // $globalVar is NOT accessible here by default
    
    // Use global keyword to access
    global $globalVar;
    echo $globalVar;
    
    // Or use $GLOBALS array
    echo $GLOBALS['globalVar'];
    
    // Static variable persists between calls
    static $count = 0;
    $count++;
    echo "Called $count times";
}

test(); // "Called 1 times"
test(); // "Called 2 times"
?>