I'd like to access a static field of a class in a static function, but the field is still <Uninitialized>
. How can I initialize this field?
<?php
final class StaticTest {
private static $lookup = array(123, 456, 789);
public static function compute() {
return StaticTest::$lookup[0];
}
}
echo 'result: ' . StaticTest::compute();
?>
As you can see in the following picture taken from the Eclipse PDT debugging the static field $lookup
is <Unitialized>
.
The error is happening because you are trying to call a private variable while not calling self
to access it.
I have given the below code a test and it seems to work. Oddly, I have also given your code a test, and that seems to work fine also.
To get around this, in your compute function, you should use this return self::$lookup[0];
instead of return StaticTest::$lookup[0];
.
Another way around this would be to change the private static $lookup = array(123, 456, 789);
to public static $lookup = array(123, 456, 789);
. Doing this, your code would work fine, but is not the recommended way.
Doing this, it should return the result you want. Think of it similar to non static classes, to access parameters (private or public) inside of a non-static class you can use $this->
, where as in a static class, you should use self::
instead. Also, not that using self::
to access a variable requires the $
to be present, where as using $this->
does not.
The answer provided by Dejv would also work, but involves using a singleton type class, which is definitely not needed for this procedure as it is instancing a new class each time, completely ignoring how static variables and functions can work.
Hope this answers your question.
Edit your code to this and it should work as you desire:
<?php
final class StaticTest{
protected static $instance;
private $lookup = array(123, 456, 789);
public function compute() {
return $this->lookup[0];
}
public static function get(){
if (!isset(self::$instance))
self::$instance = new self();
return self::$instance;
}
}
echo 'result: ' . StaticTest::get()->compute();
To explain myself here, it's always better to use the concept where you only specify that you want to use the property of object and don't care about creating the object.
It is done automatically (it object doesn't exist in memory it is created, if it exists it is called).
I can't really explain this better. I'm no braniac. I only use this concept as a substitution for application global variables.
Hope it helps!