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
| Type | Example | Notes |
|---|---|---|
string | "hello", 'world' | Double quotes parse variables; single don't |
int | 42, -7, 0xFF | Platform-dependent size (usually 64-bit) |
float | 3.14, 1.2e3 | IEEE 754 double precision |
bool | true, false | Case-insensitive |
array | [1, 2, 3] | Can be indexed or associative |
null | null | Represents 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.