Skip to content
Advertisement

Type hinting with enumerations?

I’ve read here about enumarations and their “implementation”

PHP and Enumerations

point is, why use enums, when not for type hinting?

but this implementation does not allow use for type hinting. Because the enum entries are all strings.

is there a way I can say

function($a) {

}

$a must be 'foo', 'bar' or 'baz'

in PHP?

I use phpstorm/intellij so if there is another way to do that, that would be fine too. E.g. say in the doc but with autocompletion magic from phpstorm, or maybe compile errors.

Advertisement

Answer

There is no built-in way in PHP to require that a passed string has a certain value; not even in PHP7. You can type-hint objects and arrays that I know of. Enumerations would solve that problem, but PHP doesn’t support enumerations.

If you really, really need that, maybe you should consider a strongly-typed programming language.

If you are stuck with PHP

An easy way you can make sure your string follows some rules is to make it a class that blows up if it’s not one of those values.

Try this

<?php

class WeekDay {
    private $value;

    public function __construct($value) {
        if (!in_array($value, ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']))
            throw new Exception("Not a week day.");
        else
            $this->value = $value;
    }

    public function __toString() {
        return $this->value;
    }
}

function echoWeekDay(WeekDay $weekDay) {
    echo $weekDay . "n";
}

echoWeekDay(new WeekDay("Tuesday"));
echoWeekDay(new WeekDay("Saturday"));

Run with

~/Code/stack-overflow $ php enums.php
Tuesday
PHP Fatal error:  Uncaught exception 'Exception' with message 'Not a week day.' in /Users/marianol/Code/stack-overflow/enums.php:8
Stack trace:
#0 /Users/marianol/Code/stack-overflow/enums.php(23): WeekDay->__construct('Saturday')
#1 {main}
  thrown in /Users/marianol/Code/stack-overflow/enums.php on line 8

Fatal error: Uncaught exception 'Exception' with message 'Not a week day.' in /Users/marianol/Code/stack-overflow/enums.php:8
Stack trace:
#0 /Users/marianol/Code/stack-overflow/enums.php(23): WeekDay->__construct('Saturday')
#1 {main}
  thrown in /Users/marianol/Code/stack-overflow/enums.php on line 8

By the way, enumerations are not primarily used for type-hinting on function arguments. For example, databases use enum fields to optimise storage efficiency (since enums need much less storage space than strings), and if your programming language doesn’t offer an enum data type, you have to be very careful when you retrieve, modify and persist to an enum data type back to your database.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement