Should I place variables in class or constructor? 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?


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 .


在这里找到我的'var'问题的答案PHP关键字'var'做什么?


If it belongs "to the class", put it in the class. If it belongs "to an instance of the class", put it in the constructor. It kinda sounds like you should be using the session, though.

链接地址: http://www.djcxy.com/p/96554.html

上一篇: 表达式不允许作为字段默认值

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