drsh30452 2013-12-08 10:38
浏览 13
已采纳

PHP静态初始化器

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>. PDT show that $lookup is unitialized

  • 写回答

2条回答 默认 最新

  • douduan7295 2013-12-08 11:14
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?