Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When declaring a class constant or property in PHP you can only specify a primitive values for default values. So for instance, this class declaration won't work:</p> <pre><code>class TEST { const ABC = 2 * 4; const DEF = some_function(); static $GHI = array( 'key'=&gt; 5 * 3, ); } </code></pre> <p>But this class declaration will:</p> <pre><code>class TEST { const ABC = 8; static $GHI = 15; } </code></pre> <p>These rules apply to <em>default values for class constants/properties</em> - you can always initialize other variables with the results of an expression:</p> <pre><code>$a= array( 'a'=&gt; 1 * 2, 'b'=&gt; 2 * 2, 'c'=&gt; 3 * 2, ); </code></pre> <p>The reason for this class declaration behavior is as follows: expressions are like verbs. They <em>do something</em>. Classes are like nouns: they <em>declare something</em>. A declarative statement should never produce the side-effects of an action statement. Requiring primitive default values enforces this rule. </p> <p>With this in mind we can refactor the original class as follows:</p> <pre><code>class SDK { static protected $_types= null; static public function getType($type_name) { self::_init_types(); if (array_key_exists($type_name, self::$_types)) { return self::$_types[$type_name]; } else { throw new Exception("unknown type $type_name"); } } static protected function _init_types() { if (!is_array(self::$_types)) { self::$_types= array( 'STRING_NONE'=&gt; 1 &lt;&lt; 0, // ... rest of the "constants" here 'STRING_HOSTS'=&gt; 1 &lt;&lt; 6 ); } } function __construct($fString = null) { if (is_null($fString)) { $fString= self::getType('STRING_NONE') &amp; self::getType('STRING_HOSTS'); } var_dump($fString); } } $SDK &amp;= new SDK(SDK::getType('STRING_HOSTS')); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload