Question

I need to define a constant array within the scope of an class, which is to be used statically (i.e. I am not creating an instance of the class). Here is the sample code which works in PHP5, but not in PHP4:

class MyTest {
    static $arr = array(100, 200);
    function test() {
        print_r(MyTest::$arr);
    }
}

MyTest::test();

How can I change this code so it works in PHP4 (4.4.9-pl0-gentoo)?

Remarks:

  • It has to work in PHP4.
  • I need to access the array preferrably in a static manner, without creating an instance. But this requirement could be dropped.
  • I cannot use GLOBALS as the code has to work within phpunit unit-testing. When doing so, an array defined as GLOBAL in the header of the file is not seen within the unittest.
  • I want to define the array (containing constant values) outside the function it is being used. But if no other possibility exists to solve my question, this requirement could be dropped as well.
Was it helpful?

Solution

class MyTest {
    public function getArray() {
        return array(100, 200);
    }
}

Not pretty, but you can simply call MyTest::getArray() without creating an instance (or $this->getArray() from inside the class) to retrieve the data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top