Search code examples
phpphp-parse-error

Syntax error when in a class but not out in the open?


When I do:

class MyClass {
  public $copy = file_get_contents('somefile.mdown');
}

I get:

PHP Parse error:  syntax error, unexpected '(', expecting ',' or ';' \
in /file.php on line 25

I'm new to classes in PHP, but not to OOP.

I can, of course, just do file_get_contents outside of the class and all is well. What's up with this?


Solution

  • try

    class MyClass 
    {
       public var $copy;
    
       public function MyClass()
       {
          $this->copy = file_get_contents('somefile.mdown');
       }
    };
    
    $obj = new MyClass();
    

    When I declare $copy in a class with

       public var $copy;
    

    I'm saying "When I make a thing of type MyClass it will have a member variable called 'copy'".

    Only when that class is created, and the constructor called (ie $obj = new MyClass), does $copy exist as part of some thing of type MyClass. In the constructor above (function MyClass) that thing is the $this variable, meaning "the current thing I was told to work on". In this case that might be $obj in the example above.

    Cheers, -Doug