PHP Types Tips and Tricks!

Soulaimaneyh
7 min readDec 6, 2022

--

Using types in PHP can help you write better, more robust, and more self-documenting code. It is especially useful when working with large codebases or when collaborating with other developers.

Table Of Contents

  1. how to use types in PHP?
  2. what is type hint in PHP?
  3. what is the difference between User $user and $user = new User() ?
  4. PHP Types Tips and tricks
  5. Conclusion
type hint in php

1- how to use types in php ?

To use types in PHP, you need to enable the strict_types declaration at the top of your PHP file. This tells PHP to enable strict type checking for the code in that file.

Once strict_types is enabled, you can use type declarations for function and method parameters, and for return values. For example:

declare(strict_types=1);
function sum(int $x, int $y): int
{
return $x + $y;
}

In this code, the strict_types declaration at the top of the file enables strict type checking for the code in that file. The sum() function is declared with two int parameters ($x and $y) and an int return type. This means that the function can only be called with integer arguments, and it will only return an integer value.

In this code, the strict_types declaration at the top of the file enables strict type checking for the code in that file. The sum() function is declared with two int parameters ($x and $y) and an int return type. This means that the function can only be called with integer arguments, and it will only return an integer value.

When using types in PHP, you should be aware of a few important rules and restrictions:

  • Type declarations must come before the parameter or return value name.
  • Type declarations can only be used for scalar types (bool, int, float, and string) and for class and interface names.
  • Type declarations for function and method parameters are optional, but if they are used, the corresponding arguments must be of the specified type (or of a subtype).
  • Type declarations for return values are also optional, but if they are used, the function or method must always return a value of the specified type (or of a subtype).
  • Type declarations for parameters and return values can be omitted entirely if the strict_types declaration is not enabled.

Explain PHP @mixed data type

In PHP, the mixed data type is used to represent a variable that can hold values of any data type. It is a flexible data type that can contain any value, whether it is a string, integer, float, boolean, array, object, or null.

The mixed data type allows for more dynamic coding, as it allows you to pass any type of value into a function or assign any type of value to a variable without having to worry about data type restrictions. However, it is important to note that using the mixed data type can make code harder to maintain and debug, as it can be difficult to determine the data type of a mixed variable.

Here is an example of using a mixed data type in PHP:

function calculate($num1, $num2): mixed {
if(is_numeric($num1) && is_numeric($num2)) {
return $num1 + $num2;
} else {
return "Invalid arguments";
}
}

$result1 = calculate(5, 10); // returns 15
$result2 = calculate("Hello", 10); // returns "Invalid arguments"
$result3 = calculate(3.14, true); // returns 4.14

In the example above, the calculate function takes in two parameters, $num1 and $num2, and returns their sum if they are both numeric. Otherwise, it returns the string "Invalid arguments". The return type of the function is defined as mixed, since it can return either a numeric value or a string.

The function is then called with different argument types, including an integer and a float, a string and an integer, and a float and a boolean. The mixed data type allows the function to accept these different types of arguments and return the appropriate result for each case.

2- what is type hint in PHP ?

Type hinting in PHP is a way to specify the type of a function or method parameter. This allows you to ensure that the function or method is only called with the expected type of argument. If a function or method is called with an argument of the wrong type, PHP will throw an error.

To use type hinting, you specify the type of a parameter before its name in the function or method declaration. For example:

function doSomething(int $num)
{
// This function can only be called with an integer value as the $num argument.
// The $num variable can be used here to access the integer value passed to the function.
}

In this code, the int before the $num parameter indicates that the doSomething() function can only be called with an integer value for that parameter. If the function is called with a non-integer value for the $num argument, PHP will throw an error.

Type hinting is optional in PHP, but it can be useful for ensuring that your functions and methods are called with the correct types of arguments. It also makes your code more self-documenting, as it clearly indicates the types of values that a function or method expects.

what is the difference between User $user and $user = new User() ?

3- what is the difference between User $user and $user = new User() ?

In PHP 8, the $user variable can be used in two different ways: as a type hint for the $user parameter, and as the result of instantiating the User class using the new keyword.

When used as a type hint for a function or method parameter, it indicates that the parameter must be an instance of the User class or a subclass of it. For example:

function doSomething(User $user)
{
// This function can only be called with an instance of the User class or a subclass of it.
// The $user variable can be used here to access the methods and properties of the User instance.
}

On the other hand, when used as the result of instantiating the User class, it creates a new instance of the User class and assigns it to the $user variable. This allows you to access the methods and properties of the User class using the $user variable. For example:

$user = new User();
$user->doSomething();

In this code, the new User() statement creates a new instance of the User class, and the $user->doSomething() statement calls the doSomething() method on that instance.

In short, the difference between User $user and $user = new User() is that the former is a type hint for a function or method parameter, while the latter is used to create a new instance of the User class.

For example:

declare(strict_types=1);

function printUser(User $user)
{
echo $user->name;
}

$user = new User('John Doe');
printUser($user); // Outputs: John Doe
printUser('John Doe'); // Throws a TypeError, because the argument is not of the expected type

In this code, the printUser() function is declared with a User parameter. This means that the function can only be called with an instance of the User class or a subclass of it. If the function is called with a non-User argument, PHP will throw a TypeError.

5- PHP Types Tips and tricks

1- Here is an example of using an interface type in PHP:

declare(strict_types=1);

interface Shape
{
public function getArea(): float;
}

class Circle implements Shape
{
public function __construct(
private float $radius;
) {
//
}

public function getArea(): float
{
return pi() * pow($this->radius, 2);
}
}

class Rectangle implements Shape
{
public function __construct(
private float $width,
private float $height,
) {
//
}

public function getArea(): float
{
return $this->width * $this->height;
}
}

function printShapeArea(Shape $shape)
{
echo $shape->getArea();
}

$circle = new Circle(10);
printShapeArea($circle); // Outputs: 314.16

$rectangle = new Rectangle(10, 5);
printShapeArea($rectangle); // Outputs: 50

In this code, the Shape interface defines a single method, getArea(), which must be implemented by any class that implements the Shape interface. The Circle and Rectangle classes both implement the Shape interface by implementing the getArea() method.

The printShapeArea() function is declared with a Shape parameter, so it can be called with any object that implements the Shape interface. This allows the function to accept a wide range of shapes, without needing to know their specific types.

When the printShapeArea() function is called with a Circle or Rectangle instance, it calls the getArea() method on that instance, which returns the area of the shape. This demonstrates how interfaces can be used to define common behavior for different classes, and to allow functions to accept objects of different types without needing to know their specific types.

PHP also has a special mixed type that can accept any type of value, and a void type that indicates that a function or method does not return a value.

2- Here is an example of using a class type in PHP:

declare(strict_types=1);

class User
{
public function __construct(
public string $name,
) {
//
}

public function getName(): string
{
return $this->name;
}
}

class Admin extends User
{
public function getName(): string
{
return '[Admin] ' . $this->name;
}
}

function printUserName(User $user)
{
echo $user->getName();
}

$user = new User('John Doe');
printUserName($user); // Outputs: John Doe

$admin = new Admin('Jane Doe');
printUserName($admin); // Outputs: [Admin] Jane Doe

In this code, the User class defines a name property and a getName() method. The Admin class extends the User class and overrides the getName() method to add the "[Admin]" prefix to the user name.

The printUserName() function is declared with a User parameter, so it can be called with any instance of the User class or a subclass of it. This allows the function to accept both User and Admin objects, without needing to know their specific types.

When the printUserName() function is called with a User or Admin instance, it calls the getName() method on that instance, which returns the user's name. This demonstrates how class types can be used to specify that a function or method can only be called with objects of a certain class or its subclasses.

Conclusion:

Be aware of the rules and restrictions for using types in PHP. For example, type declarations can only be used for scalar types and class/interface names, and they must come before the parameter or return value name.

If you have any idea or do you have any preferred way to declare php types, let us know in the comments section below!

--

--