Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use static constants in PHP?

Tags:

php

constants

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 
like image 726
Emanuil Rusev Avatar asked Aug 02 '10 15:08

Emanuil Rusev


People also ask

Does PHP have static variables?

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(::).

Can we use const with static?

“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.

Can we use const in PHP?

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.

What is difference between constant and static in PHP?

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.


1 Answers

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 
like image 97
Naveed Avatar answered Sep 22 '22 02:09

Naveed