doulu3399 2017-09-26 04:22
浏览 190
已采纳

在php中使用数组作为类属性

I tried to create a class with the properties like so:

class foo{

private $dbFields['test']=array("mobilePhone","address");
private $dbFields['test2']=array("mobilePhone","address",'colour');

}

but its not valid.

PHP Parse error: syntax error, unexpected '[', expecting ',' or ';' in

I had to do this which has the same result; but is less friendly for me editing in the future

class foo{

private $dbFields=array('test'=>array("mobilePhone","address"),'test2'=>array("mobilePhone","address",'colour'));

}

is there anyway to achieve the original structure or something simular?

  • 写回答

2条回答 默认 最新

  • doukekui0914 2017-09-26 04:27
    关注

    You can do it with the following class properties syntax:

    <?php
    class foo {
        private $dbFields = array(
            'test' => array("mobilePhone","address"),
            'test2' => array("mobilePhone","address","colour")
        );
    }
    

    If the values are dynamic, and not as it looks (like a reference to database columns), then you should pass the values to the class constructor as suggested by B.Desai answer.

    And if the values never change perhaps using a class constant would be nicer (PHP >=5.3.0).

    <?php
    class foo {
        const dbFields = array(
            'test'  => array("mobilePhone","address"),
            'test2' => array("mobilePhone","address","colour")
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿