PHP: assigning an object to a static property, is it illegal?

Is it possible to assign some object to a static property?

I get an HTTP 500 error below code.

require_once('class.linkedlist.php'); class SinglyLinkedlistTester { public static $ll = new Linklist(); } 

HTTP Error 500 (Internal Server Error): An unexpected condition occurred when the server tried to execute the request.

Note. There is no problem with a non-object like a string, assigning an int to a static variable. As an example,

 public static $ll = 5; //no issue 

There is also no problem with the code in the .linkedlist.php class.

+7
source share
2 answers

You cannot create new objects in class property declarations. You must use the constructor for this:

 class SinglyLinkedlistTester { public static $ll; public function __construct() { static::$ll = new Linklist(); } } 

Edit: In addition, you can test your files for errors without executing them using the PHP flag lint ( -l ):

 php -l your_file.php 

This will tell you if there are syntax or syntax errors in your file (in this case it was a parsing error).

+9
source

you should ensure that you do not override the static property with every instance of the object, so do:

 class SinglyLinkedlistTester { private static $ll; public function __construct() { if (!self::$ll) self::$ll = new Linklist(); } } 
+1
source

All Articles