简体   繁体   English

如何在PHP4中的PHP类范围内定义数组

[英]How can I define an array inside a PHP class scope in PHP4

I need to define a constant array within the scope of an class, which is to be used statically (ie I am not creating an instance of the class). 我需要在一个类的范围内定义一个常量数组,该数组将被静态使用(即,我没有创建该类的实例)。 Here is the sample code which works in PHP5, but not in PHP4: 以下是在PHP5中有效但在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)? 如何更改此代码,使其在PHP4(4.4.9-pl0-gentoo)中起作用?

Remarks: 备注:

  • It has to work in PHP4. 它必须在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. 我不能使用GLOBALS因为代码必须在phpunit单元测试中phpunit When doing so, an array defined as GLOBAL in the header of the file is not seen within the unittest. 这样做时,在单元测试中看不到文件头中定义为GLOBAL的数组。
  • 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. 但是,如果没有其他可能性可以解决我的问题,那么也可以放弃这一要求。
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. 不漂亮,但是您可以简单地调用MyTest::getArray()而不创建实例(或从类内部创建$this->getArray() )来检索数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM