Class Type Declaration in PHP

Timothy Iloba
7 min readFeb 19, 2024

Hey everyone. Welcome to this blogpost. I’m so excited about what we are about to learn in this one. Today we are going to be discussing Class type declaration in PHP. I am very sure that you are really excited and can’t wait to get to know who this new guy is. Let’s dive right in.

What is Class Type Declaration?

In PHP, Class type declarations are validation checks that help ensure that our methods receive the correct type of Objects. Trust me, it is super easy to understand. I can break it down in simpler forms.

Let’s paint a scenario. Let’s say you are going shopping and your goal is to buy your favorite kind of apples which are green apples. So, on that fateful day at the store, you pick up your shopping cart and then walk to the fruit shelf and then you begin to pick those fresh green apples to insert into your cart and as you begin to do that, something happens. A red apple and some mangoes mistakenly roll down into your cart without you noticing. They get stuck between the green apples that other green apples cover them up. You keep selecting more green apples and when you were satisfied with what you had selected, you walk to the cashier to get your items priced and then as the cashier carefully unloads your cart to count the fruits, you then notice the mangoes and red apples that fell into the cart and you were surprised. You began to ask yourself, how did these guys get in here. Lol, they got in mistakenly while you were shopping and you didn’t notice.

You see my friend, when building programs in PHP, just like you only wanted to add a specific type of apples to your cart at the shopping mall, we also want to make sure that the type of objects we pass to our methods are the type of objects we want.

We need to always make sure that the objects that are passed to our methods are the right type of objects. Class type declarations help us do that. If you can recall, we mentioned earlier that Class type declarations help us ensure that our methods receive the right type of objects. We do not want a scenario where we want an Apple object to be passed but end up receiving a Mango Object.

One good thing about Class Type Declaration is that unlike what happened at the shopping mall, where you were later surprised about those unwanted fruits that got into your cart, Class Type declaration is very fast and effective. It automatically raises an alarm when it finds out that the wrong type of object is being passed into our methods in our program. It also saves us the stress of checking each object passed into our methods ourselves.

This is how it works. As our program begins to run, it immediately scans and validates all objects that are being passed. If it finds any wrong type of object, like the odd fruits you did not need at the shopping mall, it throws an error to inform you immediately.

This behavior helps us to avoid several kinds of errors and bugs as we progress in building our applications.

I hope you have gotten a basic understanding of Class Type Declarations in PHP. It’s time for some code examples.

In this code example, we are going to be working on a simple program. In this program, let’s assume that we own a Car-shop and we sell cars.

So, we should have a class like this in our program with a method that will enable us add cars to our car-shop

<?php

class CarShop
{
public $cars = [];

public function addCar($car): void
{
$this->cars[] = $car;
}
}

From the code example above, you can see that in our car shop class, we have a cars array and an addCar method that adds cars to the cars array. In the code example above, we are just doing things the normal way without class type declarations.

So, we have settled on our car shop class, now what next, we need to be able to add cars to these carhops and for this reason, we will need to have our Car class that will help us create car objects that will be passed to our Car-shop. Take a look at the code below

<?php

class Car
{
public function __construct(public string $name, public string $color)
{

}
}

From the code example above, you can see that our car class has two properties which are the name and the color. So, we now have a class that will enable us to create Car objects that we will add to our car shop.

Let’s now go ahead and create Cars and then later add them to our car-shop. Take a look at the code below

<?php

require_once 'CarShop.php';
require_once 'Car.php';

$car1 = new Car("Mercedes GLK”, "red");
$car2 = new Car("Mercedes GLE", "green");
$car3 = “Red Mercedes Benz";

Look carefully at the code example above.

From what we have above, we can see that we have created two cars. A red Mercedes GLK and a green Mercedes GLE. Also notice that we have another fake car right there in our code. It is just a string with the words “Red Mercedes Benz”. The reason I created that fake car is to demonstrate the importance of Class Type declaration. What we will do is that in the next code example, we will add our 2 cars including the fake one into our Car shop. Take a look at the code below.

<?php


require_once 'CarShop.php';
require_once 'Car.php';

$carShop = new CarShop();
$car1 = new Car("Mercedes Benz", "red");
$car2 = new Car("Mercedes GLE", "green");
$car3 = "red Mercedes Benz";



$carShop->addCar($car1);
$carShop->addCar($car2);
$carShop->addCar($car3);

In this example above, we have created a new Car-shop and then added our 2 cars not excluding the fake Car into our it successfully. But think of it, we do not really want to sell fake cars in our car shop. I am just demonstrating this to show you the importance of Class type declaration. Let’s just assume that we didn’t know about the Fake car all along and we mistakenly added it to our Car shop.

One day, we might begin to go through our cars for inspection and in code, we can demonstrate that by looping over our cars. Take a look at the code example below

foreach ($carShop->cars as $car)
{
print $car->name;
}

If you try to loop over the cars array, you should get the following

Mercedes BenzMercedes GLEPHP Warning:  Attempt to read property "name" on string in /file/…….

What is happening here is that we tried to loop over our cars array and then after successfully looping over the first two cars and printing out their names, PHP threw an error. This is because it got to the Fake car and couldn’t loop over it because it was just a string not a real Car object.

In the first place, if we had followed good practices, we shouldn’t have even let the fake car into our car shop but because there was no check or validation (Class Type Declaration), it made it’s way into our car shop. Let’s fix that. Take a look at the code example below

<?php

class CarShop
{
public $cars = [];

public function addCar(Car $car): void
{
$this->cars[] = $car;
}
}

From the code example above, we are modifying our Car shop class and adding a Class Type declaration to our addCar method. What this simply does is that it makes sure that any Car that is going to be added into our Car shop must be of the Car class type as you can see above. In order words, it must be a real Car object not a Fake like the previous Fake Benz..lol.

Now, if we try to even add that fake car into our Car-shop, PHP will throw an error. Take a look at the code example below as from our previous example

<?php


require_once 'CarShop.php';
require_once 'Car.php';

$car1 = new Car("Mercedes Benz", "red");
$car2 = new Car("Mercedes GLE", "green");
$car3 = "red Mercedes Benz";

$carShop = new CarShop();

$carShop->addCar($car1);
$carShop->addCar($car2);
$carShop->addCar($car3);

If you run the above code, PHP will throw an error, this is because we had added Class type declarations to our addCar method which enforces that only real Cars (Cars of the Car Class Type) are added to our car shop. Take a look at the kind of error PHP will throw.

Fatal error: Uncaught TypeError: CarShop::addCar(): Argument #1 ($car) must be of type Car, string given, called in /Users/user/Desktop/blog-code-examples/class-type-declarations/class-type-declarations.php on line 15 and defined in /Users/user/Desktop/code—/class-type-declarations/CarShop.php:7

You can see that from the above error, PHP is simply saying, hey you are trying to pass a string into our Car-shop instead of an object of the Car class type.

Now my friend, go ahead and make the fake car a real car by creating it properly and then adding it to your car-shop and then try to loop over your cars and you will see that your code will run smoothly.

I hope you now understand Class Type Declarations?

Thanks for reading my friend

If you are interested in seeing this post explained in a video format, feel free to check out this full PHP Object oriented course from the guy who taught me..

https://garyclarketech.teachable.com/p/learn-object-oriented-php. Everything you need to understand Object Oriented programming is covered there.

You can grab yours now and get a 20% discount. All you have to do is use this promo code: GCTREPO20 when making your purchase.

You can access all the codes used in this post here: https://github.com/GaryClarke/blog-code-examples/tree/4-class-type-declaration

--

--

Timothy Iloba

Let's work our way up into being world class PHP developers. We will focus on understanding the basics and important concepts as that is what will set us apart.