Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Object assignment to static property, is it illegal?

Tags:

oop

php

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.

like image 791
P K Avatar asked Jan 25 '12 19:01

P K


People also ask

Can we use this in static method PHP?

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside methods declared as static. Calling non-static methods statically throws an Error.

How do you access the properties of an object in PHP?

The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties: $a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error!

Can we change static variable value in PHP?

Actually, static variables in PHP are not static at all.. their values can be changed during execution.

What is static in PHP OOP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.


2 Answers

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).

like image 199
FtDRbwLXw6 Avatar answered Oct 29 '22 14:10

FtDRbwLXw6


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();
    }
}
like image 31
staabm Avatar answered Oct 29 '22 14:10

staabm