tags:

views:

24

answers:

1

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?

+1  A: 

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

Doug T.
This was what I was working on after I wrote the question, thanks!
rpflo
Also, you need a `()` after MyClass, or else you get a syntax error.
rpflo
cool thanks :) post is updated with correction.
Doug T.
Sorry ... `public function MyClass` needs to be `public function MyClass()` Thanks again.
rpflo