0

Possible Duplicate:
Parse error: syntax error, unexpected ‘.’, expecting ‘,’ or ‘;’

I have this class:

<?php

class MyClass {
  const DB_NAME  = "MyDb";

  const HOST = "localhost"; 

  const USER = "abcdef";

  const PASSWORD = "ghijklmn";

  public static $MyString = file_get_contents('file.txt');

}
?>

I have no idea what is wrong with file_get_contents ?

I cannot understand what is the error says ? Why ( is unexpected ?

I read the following articles but these don't help me to solve that error:

Parse error: syntax error, unexpected T_STRING in php

Parse error T_Variable

file_get_contents shows unexpected output while reading a file

Community
  • 1
  • 1
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
  • You cannot initialize a class property with an expression or constant. The value has to be available at compile time. Initialize it in a static `init()` method instead. – Michael Berkowski Oct 13 '12 at 14:31
  • See the first paragraph [in these docs](http://php.net/manual/en/language.oop5.properties.php) – Michael Berkowski Oct 13 '12 at 14:32
  • Even in a constructor ? Can I use in a constructor ? – Snake Eyes Oct 13 '12 at 14:35
  • Usually you initialize it in the contstructor, but since yours is static, you wouldn't necessarily be instantiating via a constructor first. That's why I suggest a static `init()` method to initialize static properties. See the linked duplicate - there's a comparable example there. – Michael Berkowski Oct 13 '12 at 14:37

1 Answers1

3

It's because you have assigned expression to variable declaration. It can only use constants.

The workaround would be like this

<?php
class MyClass {
    ...
    public static $MyString;
    ...
}
MyClass::$MyString = file_get_contents('file.txt');
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71