PHP: Object assignment to static property, is it i

2020-04-03 16:01发布

Is it illegal to assign some object to static property?

I am getting HTTP 500 error in below code.

require_once('class.linkedlist.php');

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

HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfil the request.

Note: No issue with non object like string,int assignment to static variable. As an example,

public static $ll = 5; //no issue

Also there is no code issue in class.linkedlist.php.

标签: php oop
2条回答
ゆ 、 Hurt°
2楼-- · 2020-04-03 16:46

you should take care, that you don't override the static property on each instantiation of a object, therefore do:

class SinglyLinkedlistTester {
    private static $ll;

    public function __construct() {
        if (!self::$ll) self::$ll = new Linklist();
    }
}
查看更多
对你真心纯属浪费
3楼-- · 2020-04-03 16:55

You can't create new objects in class property declarations. You have to use the constructor to do this:

class SinglyLinkedlistTester {
    public static $ll;

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

Edit: Also, you can test your files for errors without executing them using PHP's lint flag (-l):

php -l your_file.php

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

查看更多
登录 后发表回答