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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 关于c++外部库文件宏的问题,求解
  • ¥15 office打开卡退(新电脑重装office系统后)
  • ¥300 FLUENT 火箭发动机燃烧EDC仿真
  • ¥15 【Hadoop 问题】Hadoop编译所遇问题hadoop-common: make failed with error code 2
  • ¥15 vb6.0+webbrowser无法加载某个网页求解
  • ¥15 RPA财务机器人采购付款流程
  • ¥15 计算机图形多边形及三次样条曲线绘制
  • ¥15 根据protues画的图用keil写程序
  • ¥200 如何使用postGis实现最短领规划?
  • ¥15 pyinstaller打包错误