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
Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both. The variables and methods are accessed without the creation of an object, using the scope resolution operator(::).
“static const” is basically a combination of static(a storage specifier) and const(a type qualifier). The static determines the lifetime and visibility/accessibility of the variable.
PHP introduced a keyword const to create a constant. The const keyword defines constants at compile time. It is a language construct, not a function. The constant defined using const keyword are case-sensitive.
Constant is just a constant, i.e. you can't change its value after declaring. Static variable is accessible without making an instance of a class and therefore shared between all the instances of a class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With