tags:

views:

62

answers:

3

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);
+4  A: 

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

Sarfraz
OOO, exacly! That i would like achieve! But what if my class has smth in construcotr? I can't do it like: `$x = new Types::car(123);` ... :(
John X
@John: Instantiate a variable class by assigning the constant value to a variable first: `$type = Types::car; $x = new $type(123);`
BoltClock
+1  A: 

It's a constant. You can't change it. So it doesn't make any sense that you'd have a non-static constant member. So you don't have to declare them as static or class variables.

Sean
+1  A: 

Constants are already static in the sense that they aren't tied to an instance of the class. Here is how to define them and use them as you want:

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

$x = Types::car;
ryeguy
You mean `Types::car`. Other than that, +1
Pekka