Var constants inside class class

class Constants { public static $url1 = "http=//url1"; public static $url2 = Constants::$url1."/abc2"; public static $url3 = Constants::$url1."/abc3"; public static $url4 = Constants::$url1."/abc4"; } 

I know this is impossible

so I have to use it as if you had a restriction of $ url1 in one place

 class urlOnly { public static $url1 = "http=//url1"; } class Constants { public static $url1 = urlOnly::$url1; public static $url2 = urlOnly::$url1."/abc2"; public static $url3 = urlOnly::$url1."/abc3"; public static $url4 = urlOnly::$url1."/abc4"; } 

Also, if I want to use this, can I make sure that the "urlOnly" class can only be accessed by the "Constants" class.

An alternative solution is most welcome, since in this solution I need to create two classes. Also, I want to access the variable only as a variable, and not as a function, and I want it to be accessed as static

0
source share
3 answers

You cannot use non-scalar values ​​in a class definition. Use define() instead.

+1
source

One thing you can do to achieve what you are looking for is this:

 class Constants { public static $url1 = "http://url1"; public static $url2 = ""; // etc } Constants::$url2 = Constants::$url1 . "/abc2"; 

Unfortunately, to dynamically determine static values, you will have to do this outside the context of the class, because static variables can only be initialized with literals or variables (so there was a parsing error in the previous version of this answer).

However, I would recommend using define instead, as it is designed to define constant values, and there is no reason to store constants inside the class context if that makes absolutely no sense (at least in my opinion).

Sort of:

 define("URL1", "http:://url1"); define("URL2", URL1 . "/abc2"); 

Then you do not need to specify the accessory of the class, just use URL1 or URL2 as necessary.

0
source

As a rule, it is impossible to declare dynamic constants and static properties without calling class methods. But you can implement the logic you need. You must use placeholders in strirngs constants. Then you must add the static "get" method to extract the constants and replace the placeholders. Like this:

 class Constants { protected static $config = array( 'url1' => 'http=//url1', 'url2' => '%url1%/abc2', 'url3' => '%url1%/abc3', 'url4' => '%url1%/abc4', ); public static function get($name, $default = null) { if (!empty(self::$config[$name]) && is_string(self::$config[$name]) && preg_match('/%(\w[\w\d]+)%/', self::$config[$name], $matches)) { self::$config[$name] = str_replace($matches[0], self::$config[$matches[1]], self::$config[$name]); } return self::$config[$name]; } } 

How to use:

 Constants::get('url1'); Constants::get('url2'); Constants::get('url3'); Constants::get('url4'); 
0
source

All Articles