drt5813 2017-04-26 03:04
浏览 210

Php设置变量属性默认值在php 7.1中不起作用

I have a variable property set default value array, it works in my php 5.6 localhost but not working when i upload to server with php 7.1 , can anyone tell me why?

class foo {
    var $bar = array();

    function baz($data) {
        $this->bar['data'] = $data; <---- works in php 5.6, not working in php 7.1
    }
}

in php 7.1, I have to update variable property in construct

function __construct(){
    $this->bar = array();
}
  • 写回答

1条回答 默认 最新

  • drhg24275 2019-02-17 22:52
    关注

    The code you provided produces very same result from PHP version 7.1.25 to 7.3.2 (check on 3v4l.org):

    object(foo)#1 (1) {
      ["bar"]=>
      array(1) {
        ["data"]=>
        int(22)
      }
    }
    

    Even it works, I would suggest ALWAYS initializing class properties in __construct as you discovered too:

    function __construct(){
        $this->bar = array();
    }
    

    more importantly, prefer using one of public/protected or private visibility modifiers, rather than var which turns into a public under the hood.

    评论

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染