← Back to Chapters

PHP OOP Type Hinting

? PHP OOP Type Hinting

? Quick Overview

Type Hinting in PHP allows developers to specify the expected data type of parameters and return values. This improves code reliability, readability, and prevents invalid data from entering functions or methods.

? Key Concepts

  • Primitive types: int, float, string, bool
  • Array type: array
  • Object type: specific class names
  • Union types: int|string
  • Nullable types: ?int
  • Return type declarations

? Syntax & Theory

Type hints are placed before parameters, and return types are declared after the method signature using a colon. PHP validates the type at runtime.

? Basic Code Example

? View Code Example
// Basic type hinting with parameters and return types
add(5, 10);
echo "
";
echo $calc->greet("Alice");
?>

? Object Type Hinting

? View Code Example
// Enforcing object types in method parameters
name = $name;
}
}

class UserService {
public function printUser(User $user): void {
echo "User: " . $user->name;
}
}

$user = new User("Bob");
$service = new UserService();
$service->printUser($user);
?>

? Advanced Examples

? View Code Example
// Union and nullable type hinting
double(5);
echo "
";
$math->setAge(null);
?>

? Live Output & Explanation

The output shows how PHP strictly enforces data types and safely handles multiple allowed types or nullable values.

? Use Cases

  • Validating user input
  • Building large OOP-based applications
  • Reducing runtime bugs
  • Improving IDE autocomplete and documentation

✅ Tips & Best Practices

  • Use declare(strict_types=1); for strict checking
  • Always define return types
  • Use union and nullable types carefully
  • Keep method signatures clean and clear

? Try It Yourself

  • Create a function using int parameters and test invalid values
  • Write a class that only accepts object parameters
  • Experiment with union types
  • Test nullable types using null