Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - why I couldn't declare static const variable?

Tags:

oop

php

I would use them to implement factory pattern, for example:

class Types{
   static const car = "CarClass";
   static const tree = "TreeClass";
   static const cat = "CatClass";
   static const deathstar = "DeathStarClass";
}

And I would like to use them like:

$x = new Types::car;

Is it possible?

And what if my class has parametr in construcor, that doesn't work:

$x = new Types::car(123);
like image 521
John X Avatar asked Oct 28 '10 19:10

John X


1 Answers

Your code should be:

class Types{
   const car = "CarClass";
   const tree = "TreeClass";
   const cat = "CatClass";
   const deathstar = "DeathStarClass";
}

Note that since constants are tied to the class definition, they are static by definition.

From Docs:

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

http://www.php.net/manual/en/language.oop5.static.php

More Info:

http://php.net/manual/en/language.oop5.constants.php

like image 58
Sarfraz Avatar answered Oct 05 '22 22:10

Sarfraz