Understanding Class Type Declarations in PHP
This article explains PHP class type declarations, using a fruit‑shopping analogy and step‑by‑step code examples that show how to define Car and CarShop classes, enforce type safety with type hints, and avoid runtime errors caused by passing incorrect object types.
In PHP, class type declarations act as a validation mechanism that ensures methods receive objects of the expected class, preventing type‑mismatch errors.
The article uses a shopping‑cart analogy to illustrate how unwanted items (incorrect types) can slip into a collection if not properly checked.
It then introduces a simple CarShop example, showing a class with a $cars array and an addCar method that initially lacks type hints.
<?php
class CarShop
{
public $cars = [];
public function addCar($car): void
{
$this->cars[] = $car;
}
}A Car class is defined with public properties $name and $color using a constructor.
<?php
class Car
{
public function __construct(public string $name, public string $color)
{
}
}Instances of Car are created and added to the CarShop, but a string (a “fake car”) is also added, demonstrating the problem when type declarations are missing.
<?php
require_once 'CarShop.php';
require_once 'Car.php';
$car1 = new Car("Mercedes GLK", "red");
$car2 = new Car("Mercedes GLE", "green");
$car3 = "red Mercedes"; // not a Car object
$carShop = new CarShop();
$carShop->addCar($car1);
$carShop->addCar($car2);
$carShop->addCar($car3);When iterating over $carShop->cars, PHP throws a warning because the third element is a string, not a Car object.
foreach ($carShop->cars as $car) {
print $car->name;
}To fix the issue, the addCar method is updated with a class type declaration addCar(Car $car): void, forcing only Car objects to be added.
<?php
class CarShop
{
public $cars = [];
public function addCar(Car $car): void
{
$this->cars[] = $car;
}
}Running the corrected code results in a fatal TypeError when a string is passed, demonstrating how class type declarations protect against invalid data.
Fatal error: Uncaught TypeError: CarShop::addCar(): Argument #1 ($car) must be of type Car, string given...The article concludes that using class type declarations ensures type safety, improves code reliability, and prevents runtime errors caused by incorrect object types.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
