Thursday 18 January 2018

Parse error Unexpected (, expected , in php when assign content file to a static property













I
have this
class:




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:



href="https://stackoverflow.com/questions/11785017/parse-error-syntax-error-unexpected-t-string-in-php">Parse
error: syntax error, unexpected T_STRING in
php




href="https://stackoverflow.com/questions/8353629/parse-error-t-variable">Parse error
T_Variable



href="https://stackoverflow.com/questions/9720861/file-get-contents-shows-unexpected-output-while-reading-a-file">file_get_contents
shows unexpected output while reading a file



Answer




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



The workaround would be like
this



class
MyClass {

...
public static $MyString;

...
}
MyClass::$MyString =
file_get_contents('file.txt');


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...