dave
dave

Reputation: 7857

parse error setting a variable in PHP

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.

Upvotes: 3

Views: 100

Answers (2)

Andrew Moore
Andrew Moore

Reputation: 95334

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().

Upvotes: 3

Darryl Hein
Darryl Hein

Reputation: 144967

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;

?>

Upvotes: 2

Related Questions