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 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合