Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 338
Tim Avatar asked Aug 19 '10 03:08

Tim


1 Answers

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.

like image 52
Ed Mazur Avatar answered Sep 24 '22 03:09

Ed Mazur