tags:

views:

65

answers:

2

I have a config class which gets used throughout my code. One variable within this class is the website URL. Recently, I added SSL to my server and now I need to check for this and assign either '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 produces a parse error. How do I fix it? :/

+2  A: 

You can't use a calculation to determine an object property value. You'll need to do this:

<?php

class Test
{
   public static $blah;
}

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


echo Test::$blah;

?>
Darryl Hein
+3  A: 

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

What you can do is create an "Static Initializer" function which can only be called once and will set your variables... As such:

<?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();

And then simply fetch your variable from your other file:

<?php
echo Test::$blah;

If you edit Test::$blah later in the code, it will not be reverted by an accidental call to Test::__initStatic().

Andrew Moore
+1 That's a really interesting design pattern / workaround for php. Throwing a function call into a class file feels a little dirty, but it'll work,
Chris Henry
@Chris Henry: sometimes you have to get yourself dirty when working with PHP. You definitely do not want to see my custom Error/Exception/RunTime_Err handling library.
Andrew Moore
@Andrew. A little off topic, but awhile ago my band recorded an album. When we were mastering, the recordings weren't perfect. The engineer told us "It's not rock n roll unless there's a little dirt on it". PHP is no different.
Chris Henry