Search code examples
phpclassvariablessyntaxconstants

Can you use static constants inside classes in PHP?


I expected the following to work but it doesn't seem to.

<?php

class Patterns
{
    public static const EMAIL = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";
    public static const INT = "/^\d+$/";
    public static const USERNAME = "/^\w+$/";
}

Because it throws this error:

syntax error, unexpected T_CONST, expecting T_VARIABLE

Solution

  • You can use const in class like this:

    class Patterns {
        const EMAIL = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";
        const INT = "/^\d+$/";
        const USERNAME = "/^\w+$/";
    }
    

    And can access USERNAME const like this:

    Patterns::USERNAME