Sounds silly, but ... I need help setting a variable in PHP

I have a configuration class that is used throughout my code. One variable in this class is the website URL. I recently added SSL to my server, and now I need to check this and set "http" or "https" as the protocol.

The code I tried is:

<?php

class Test
{
   public static $blah = (1 == 1) ? 'this' : 'or this';
}

echo Test::$blah;

?>

This creates a parsing error. How to fix it?:/

+3
source share
2 answers

Unfortunately, you cannot set class variables by default using expressions. You can use only primitive types and values. Only array()recognized.

, " ", ... :

<?php

class Test
{
   public static $blah;
   private static $__initialized = false;

   public static function __initStatic() {
       if(self::$__initialized) return;

       self::$blah = (1 == 1) ? 'this' : 'or this';

       self::$__initialized = true;
   }
}
Test::__initStatic();

:

<?php
echo Test::$blah;

Test::$blah , Test::__initStatic().

+3

. :

<?php

class Test
{
   public static $blah;
}

// set the value here
Test::$blah = (1 == 1) ? 'this' : 'or this';


echo Test::$blah;

?>
+2

Source: https://habr.com/ru/post/1757276/


All Articles