views:

41

answers:

4

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?

A: 

Found the answer to my 'var' question here http://stackoverflow.com/questions/1206105/what-does-php-keyword-var-do

Tim
A: 

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.

jeremiahd
+2  A: 

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.

Edward Mazur
Can't you also declare them like: $this->my_data = array(); and have it available anywhere in the class?
EvilChookie
@evilchookie - yes, but it's nicer to have a list of variables being used at the top
Galen
A: 

its fine if you declare the variable outside constructor. actually codeigniter will not let you give any parameter at your constructor. and the variable will automatically assigned value when the class is instantiated. for default, any of php variable and function with in a class will be have a public access. i don't really thing you need to use access modifier at codeigniter. the library it self don't define any access modifier.

Swing Magic