PHP supports 8 primitive data types categorized into Scalar, Compound, and Special types. Starting with PHP 8, PHP features a strong type system with explicit type hints, union types, and nullable types.
flowchart TD
A["PHP Data Types"] --> B["Scalar Types (Single Value)"]
A --> C["Compound Types (Multiple Values)"]
A --> D["Special Types"]
B --> B1["string"] & B2["int"] & B3["float / double"] & B4["bool"]
C --> C1["array"] & C2["object"] & C3["callable"] & C4["iterable"]
D --> D1["null"] & D2["resource"]
// Check data type
gettype($val);
is_int($val);
is_string($val);
is_array($val);
// Explicit Type Casting
$count = (int)"42";
$price = (float)"19.99";
$isMember = (bool)1;
<?php
declare(strict_types=1);
class UserProfile
{
public function __construct(
public string $username,
public int $age,
public float $rating,
public bool $isActive,
public ?string $bio = null // Nullable type
) {}
}
// Creating Compound Object Data Type
$user = new UserProfile("maksudur", 28, 4.95, true, "Senior Software Architect");
// Array (Compound Type)
$skills = ["PHP 8", "Laravel", "MySQL", "Docker"];
// Resource (Special Type)
$fileResource = fopen(__FILE__, "r");
echo "Username Type: " . gettype($user->username) . "
";
echo "Age Type: " . gettype($user->age) . "
";
echo "Skills Type: " . gettype($skills) . "
";
echo "File Resource Type: " . gettype($fileResource) . "
";
fclose($fileResource);
declare(strict_types=1); at top of files to prevent unintended implicit type coercion.?type and Union Types typeA|typeB: Explicitly declare when parameters or returns can accept null or multiple distinct types.var_dump() or get_debug_type() for Debugging: get_debug_type() in PHP 8 gives precise class names and type details.Create a function processScore(int|float $score): string that uses PHP 8 union types to accept either an integer or float score and returns "Passed" if score >= 50!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.