Theory
Variables & Data Types
PHP 8.3.8
Core Concepts

Variables & Data Types

Topic 2 of 13

PHP is dynamically typed by default โ€” variables hold any type and can change. PHP 8 added strict typing, union types, and readonly for production-quality code.

PHPvariables.php
<?php
// Variables always start with $
$name    = "Nishu";        // string
$age     = 21;              // integer
$gpa     = 9.1;             // float
$active  = true;            // boolean
$nothing = null;            // NULL

// Type inspection
var_dump($age);     // int(21)
gettype($name);   // "string"

// Type casting
$num = (int)"42abc";   // 42
$str = (string)3.14;  // "3.14"

// Constants (no $ prefix)
define('MAX_SIZE', 100);
const APP_NAME = 'PHPForge';

// PHP 8 โ€” Typed declarations
function greet(string $name, int $age): string {
    return "$name is $age years old";
}

// Nullable type (?type means string OR null)
function findUser(int $id): ?string {
    return $id === 1 ? "Nishu" : null;
}

// PHP 8.1 readonly property (set once in constructor)
class User {
    public readonly string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
}

PHP Data Types

TypeExampleNotes
string"hello", 'world'Double quotes parse variables; single don't
int42, -7, 0xFFPlatform-dependent size (usually 64-bit)
float3.14, 1.2e3IEEE 754 double precision
booltrue, falseCase-insensitive
array[1, 2, 3]Can be indexed or associative
nullnullRepresents no value
โš ๏ธ Loose vs Strict
Add declare(strict_types=1); at the very top of every file to enforce strict type checking โ€” prevents silent coercion bugs like "5" + 3 silently becoming 8.