DEV Community

Karleb
Karleb

Posted on • Updated on

Return Types In PHP

Return types in PHP refer to the type of data returned by a function in PHP. In strongly typed languages like JAVA, every function must have a return type but it is optional in PHP as it is a loosely typed programming language. It is a good practice to include return types as it reduces ambiguity, limits error and improves code quality.

We will be looking into several return types in PHP. Without any further ado, let's dive in.

Prerequisite

  • PHP version 8

  • Basic knowledge of PHP

To enforce return type in PHP functions, we need to include a simple declaration at the top of the file.

declare(strict_types=1);
Enter fullscreen mode Exit fullscreen mode

This is a PHP directive that enforces strict typing. It is used to ensure that only values of the expected data type are passed to a function or method.

When strict_types is set to 1, PHP will require that function arguments are of the correct data type. If an argument is of the wrong type, PHP will throw a TypeError instead of attempting to convert the argument to the expected type.

With this in place, we can be rest assured PHP is not doing any type conversion that we may not be aware of when incorrect types are used.

The type of data we want the function or method to return is declared by putting a colon and the type between the closing parenthesis and the opening curly bracket.

int

int return type represents integers in PHP. They are positive or negative whole numbers without decimals, int can also be zero.


function addition(int $a, int $b): int {
  $sum  = $a + $b;
  return $sum;
}

echo addition(12, 20);
Enter fullscreen mode Exit fullscreen mode

In class example:


class Arithmetic {
  public function __construct(public int $a, public  int $b) {}

  public function addition(): int {
    $sum = $this->a + $this->b;
    return $sum;
  }
}

echo (new Arithmetic(12, 20))->addition();
Enter fullscreen mode Exit fullscreen mode

string

The string is a return type used to represent text. It can contain any sequence of characters, including letters, numbers, symbols, and whitespace.

Strings can be declared using a single or double quote.


function greeting(): string {
 return "Good day fellow!";
}

echo greeting();
Enter fullscreen mode Exit fullscreen mode

class Greeting {
  public function __construct(public string $message) {}

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

echo (new Greeting("Good day fellow!"))->greeting();
Enter fullscreen mode Exit fullscreen mode

float

Float is a return type used to represent numbers with a decimal point. Floats are also known as "floating point numbers" or "doubles".


function price(): float {
  return 10.56;
}

echo price();
Enter fullscreen mode Exit fullscreen mode

class Socks {
  public function price(): float {
    return 10.56;
  }
}

(new Socks())->price();
Enter fullscreen mode Exit fullscreen mode

Floats can be negatives too.


function price(): float {
  return -1.78;
}

echo price();
Enter fullscreen mode Exit fullscreen mode

class Socks {
  public function price(): float {
    return -1.78;
  }
}

(new Socks())->price();
Enter fullscreen mode Exit fullscreen mode

bool

bool, short for "boolean", is a return type used to represent logical values. A bool variable can only have two possible values: true or false.

It is important to note that PHP returns 1 for true and nothing for false.


function isComplete(): bool {
  return true;
}

echo isComplete();


function isAdult(int $age): bool {
  return $age >= 18;
}

echo isAdult(10);
Enter fullscreen mode Exit fullscreen mode

class Task {
  public function isComplete(): bool {
    return true;
  }
}

class Person {
   public function isAdult(int $age): bool {
    return $age >= 18;
  }
}

echo (new Task)->isComplete();
echo (new Person)->isAdult(2);
Enter fullscreen mode Exit fullscreen mode

array

The array is a return used when a method or function is expected to return an array. PHP has index, associative and multidimensional arrays, any of these can be returned when an array return value is used.


function playlist(): array {
  return ['Diced Pineapple', 'Formation', 'Thinking Out Loud'];
}

print_r(playlist());

function user(): array {
  return ['name' => 'John', 'age' => 25, 'location' => 'New York'];
}

print_r(user());
Enter fullscreen mode Exit fullscreen mode

class Playlist {
  public function music(): array {
    return ['Diced Pineapple', 'Formation', 'Thinking Out Loud'];
  }

  public function user(): array {
    return ['name' => 'John', 'age' => 25, 'location' => 'New York'];
  }
}

print_r(
  (new Playlist)->music()
);

print_r(
  (new Playlist)->user()
);
Enter fullscreen mode Exit fullscreen mode

void

In the case we do not wish to return anything, the void is the goto return type. It simply means nothing will be returned.


function earth(): void {
  $title = "This planet supports life";
  $age_in_years = 4_800_000_000;
}

earth();
Enter fullscreen mode Exit fullscreen mode

class Planet {
  public function earth(): void {
    $title = "This planet supports life";
    $age_in_years = 4_800_000_000;
  }
}

(new Planet)->earth();
Enter fullscreen mode Exit fullscreen mode

mixed

A mixed return type is used to indicate that a function or method may return different data types, depending on the input or the logic within the function. This is helpful when you cannot determine the exact return type ahead of time, or when the return type is dependent on a complex set of conditions.


function randomType(): mixed {

    $value;

    switch(rand(1, 5)) {

      case 1: $value = "Good day fellow!";
      break;
      case 2: $value = 10.22;
      break;
      case 3: $value = true;
      break;
      case 4: $value = ['Sport', 'Movies'];
      break;
      default: $value = 100;
      break;

    }

    return $value;
}

echo randomType();
Enter fullscreen mode Exit fullscreen mode

class RandomType {
  public function value(): mixed {

    $value;

    switch(rand(1, 5)) {

      case 1: $value = "Good day fellow!";
      break;
      case 2: $value = 10.22;
      break;
      case 3: $value = true;
      break;
      case 4: $value = ['Sport', 'Movies'];
      break;
      default: $value = 100;
      break;

    }

    return $value;

  }
}


echo (new Randomtype)->value();
Enter fullscreen mode Exit fullscreen mode

callable

The callable return type in PHP allows a function to indicate that it returns a callable or a function reference that can be called later.


function getMultiplier(int $factor): callable {
    return function (int $number) use ($factor) {
        return $number * $factor;
    };
}

$multiplyByTwo = getMultiplier(2);
echo $multiplyByTwo(5); 


$multiplyByThree = getMultiplier(3);
echo $multiplyByThree(6);
Enter fullscreen mode Exit fullscreen mode

class Multiplier {

    public function __construct(public int $factor) {}

    public function getMultiplier(): callable {
        return function (int $number) {
            return $number * $this->factor;
        };
    }
}

$multiplyByTwo = (new Multiplier(2))->getMultiplier();
echo $multiplyByTwo(5);

$multiplyByThree = (new Multiplier(3))->getMultiplier();
echo $multiplyByThree(6);
Enter fullscreen mode Exit fullscreen mode

resource

The resource return type is used to indicate that a function or method returns a resource type. Resource type is a special data type that represents an external resource, such as a file, a database connection or a network socket.


function openFile(string $filename): resource {

  $file = fopen($filename, "r");

  if (!$file) {
    throw new Exception("Failed to open file: $filename");
  }

  return $file;

}
Enter fullscreen mode Exit fullscreen mode


class FileHandler {

  public function openFile(string $filename): resource {

    $file = fopen($filename, "r");

    if (!$file) {

      throw new Exception("Failed to open file: $filename");

    }

    return $file;

  }

}
Enter fullscreen mode Exit fullscreen mode

class

Classes can also be a return type. In this example, the Zoo class has a method called getAnimal() that returns an object of the Animal class. The return type of this method is specified as Animal using the :Animal syntax after the method signature. This means the return type will be a type of Animal class or any of its subclasses.


class Animal {
  public function __construct(public string $name, public int $age) {}
}

function getAnimal(): Animal {
    return new Animal("Leo", 5);
}

print_r(getAnimal());
Enter fullscreen mode Exit fullscreen mode

class Animal {
  public function __construct(public string $name, public int $age) {}
}

class Zoo {
  public function getAnimal(): Animal {
    return new Animal("Leo", 5);
  }
}

print_r((new Zoo())->getAnimal());
Enter fullscreen mode Exit fullscreen mode

object

The object return type is similar to the :class return type but the major difference is, it will return instances of any class and not a particular class.


class Address {
  public function __construct(public string $street, public string $city, public string $state) {}
}

class Person {
  public function __construct(public string $name, public Address $address) {}

  public function getAddress(): object {
    return $this->address;
  }
}

$address = new Address("123 Main St", "Anytown", "CA");
$person = new Person("John Doe", $address);
$addressObj = $person->getAddress();
Enter fullscreen mode Exit fullscreen mode

Note that since the return type of getAddress() is specified as :object, the returned value can be an instance of any class, not just Address.

union

What if we can not tell the actual type a class should return or do we want to intentionally make the return type for any class dynamic?

PHP allows us to include additional return types using the union type, this allows us to include alternate types by separating them with a pipe |.


function price(): int | float {
  return 10;
}

function price(): int | float {
  return 10.4;
}
Enter fullscreen mode Exit fullscreen mode

class Socks {
  public function price(): int | float {
    return 10;
  }
}

(new Socks)->price();

class Socks {
  public function price(): int | float {
    return 10.4;
  }
}

(new Socks)->price();
Enter fullscreen mode Exit fullscreen mode

The optional type can have as many as possible types separated by a pipe, this feature should not be abused.

What If We Want a Null Value Returned

To return a null type, we need to add ? in front of the return type.


function hello(): ?string {
  return null;
}

hello();
Enter fullscreen mode Exit fullscreen mode

In this case, the return type of the function can be either a string or null. No exception will be thrown.


class Optional {

  public function hello(): ?string {
    return null;
  }

  public function number(): ?int {
    return null;
  }

  public function price(): ?float {
    return null;
  }
}

echo (new Optional)->hello();
echo (new Optional)->number();
echo (new Optional)->price();
Enter fullscreen mode Exit fullscreen mode

Conclusion

Return types are an important feature in PHP that allows developers to specify the type of value that a function should return. By declaring a return type, PHP can ensure that the value returned by a function is of the expected type, which can help prevent errors and improve code quality.

In PHP 7 and later versions, developers can use several different types of return types, including scalar types like int, float, and string, as well as compound types like array and callable. Additionally, PHP 8 introduced new return types, including union types and mixed types, which provide even more flexibility for developers.

Type declarations in PHP can be used not only for return types but also for parameter types and class properties. Type declarations can help prevent type errors, improve code readability, and make code easier to maintain.

Top comments (1)

Collapse
 
cawa93 profile image
Alex Kozack • Edited

How to declare method that return not a class instance but a class itself?



class Zoo {
  public function getAnimal(): ???? {
    return Animal::class
  }
}


Enter fullscreen mode Exit fullscreen mode