Tim
Tim

Reputation: 2697

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?

Upvotes: 5

Views: 5094

Answers (3)

Jeg Bagus
Jeg Bagus

Reputation: 5075

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.

Upvotes: 0

Ed Mazur
Ed Mazur

Reputation: 3102

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.

Upvotes: 7

jdd
jdd

Reputation: 4336

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.

Upvotes: 0

Related Questions