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

时光毁灭记忆、已成空白 提交于 2019-12-12 05:12:20

问题


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:


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



来源:https://stackoverflow.com/questions/1653302/syntax-error-when-in-a-class-but-not-out-in-the-open

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!