Skip to content

Chapter 4 of 7

The PHP Type System

Since PHP 7, type declarations have become a cornerstone of robust PHP code. Type hints let you declare the expected types of function parameters and return values, enabling PHP's runtime to catch mismatches before they cause subtle bugs. For instance, declaring a function that accepts two int parameters and returns an int ensures that the caller respects the contract. When types do not match, PHP throws a TypeError rather than silently coercing the data.

By default PHP operates in coercive mode, attempting to convert values into the expected type whenever possible. You can opt into stricter behavior by placing declare(strict_types=1); at the top of a file, which forces PHP to throw a TypeError on any type mismatch without attempting coercion. Strict mode is widely recommended for new projects because it eliminates ambiguity and surfaces bugs earlier in the development cycle.

PHP 8 expanded the type system further. Union types let you declare that a parameter or return value may be one of several listed types, written as TypeA|TypeB. This is useful when a function legitimately accepts multiple input forms, such as a string or integer that both can be processed. Closely related is the nullable type syntax, where prefixing a type with a question mark, as in ?User, indicates that the value may be the specified type or null. Together, these features allow you to express precise contracts at the boundary between components, catching misuse while still accommodating realistic data shapes.

All chapters
  1. 1Object-Oriented Foundations
  2. 2Inheritance, Interfaces, and Traits
  3. 3Namespaces and Dependency Management
  4. 4The PHP Type System
  5. 5Working with Arrays and Strings
  6. 6Databases, Sessions, and Error Handling
  7. 7Closures, Generators, and Magic Methods

Drill it

Reading is not remembering. These come from the Php Programming deck:

Q

What is a class in PHP OOP?

A class is a blueprint for creating objects. It defines properties (variables) and methods (functions) that the objects will have.class User { public string $na...

Q

What is the difference between public, protected, and private visibility in PHP?

public – accessible from anywhere.protected – accessible within the class and its subclasses.private – accessible only within the defining class.These are known...

Q

How do you create an object from a class in PHP?

Use the new keyword:$user = new User();This calls the class constructor (__construct) if one is defined.

Q

What is the purpose of the __construct() magic method?

__construct() is the constructor that runs automatically when an object is created with new.public function __construct(public string $name) {}It initializes ob...