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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?