Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.

Blog

Overview

© 2024 by Frank Perez.

Void Return Types in PHP

As of PHP 7.1, we can now use void return types within our methods. This is useful for cases where you have methods that are just setting or processing data with out the need of returning any values.

Functions or Methods declared with void as their return type would simply use an empty return statement or not use a return statement at all.

Let’s look at an example below where we create a Product class capable of setting a product’s name through the constructor or a setName method. The setName method would have a return type of void, since it’s only setting a value and not set up to return anything.

<?php

class Product
{
    private $name;

    public function __construct(string $name = '')
    {
        $this->name = $name;
    }

    public function setName(string $name) : void
    {
        $this->name = $name;
    }

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

You could also just set a blank return statement like so.

public function setName(string $name) : void
{
  $this->name = $name;

  return;
}