duanpu1111 2010-08-19 03:59
浏览 28
已采纳

我应该在类或构造函数中放置变量吗? PHP

My question(s) is one of best practices for OOP. Im using Codeigniter framework/PHP.

I have a class:

class Test() {

    var $my_data = array();

    function my_function() {

        //do something

    }

}

Is it ok to declare $my_data in the class like that? or should it go in the constructor? Basically every function will be writing to $my_data so in a sense it will be a class-wide variable(global?, not sure about the terminology)

Also, should I use var or private ? is var deprecated in favor of declaring the variables scope?

  • 写回答

3条回答 默认 最新

  • dongqiu3254 2010-08-19 04:12
    关注

    If you want $my_data to be available to all methods in Test, you must declare it at the class level.

    class Test {
    
        private $my_data1 = array(); // available throughout class
    
        public function __construct() {
            $my_data2 = array(); // available only in constructor
        }
    
    }
    

    var is deprecated and is synonymous with public. If $my_data doesn't need to be available outside of Test, it should be declared private.

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

报告相同问题?

悬赏问题

  • ¥30 数字信号处理实验报告
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程