Should I put variables in a class or constructor? Php

My question is one of the 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 possible to declare $ my_data in a class? or should it go in the constructor? Basically, each function will write in $ my_data, so in a sense it will be a class variable (global ?, not sure of the terminology)

Also, should you use var or private? var is deprecated in favor of declaring a variable scope?

+5
source share
4 answers

If you want to $my_databe available for 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 public. $my_data Test, private.

+7

"var" PHP var?

0

"", . " ", . , .

0

its fine if you declare an external constructor variable. in fact, codeigniter will not allow you to specify any parameter in your constructor. and the variable automatically assigns a value when you instantiate the class. by default, any php variable and function with a class will have public access. I really do not want to use the access modifier in the code of the generator. in the library, he himself does not define an access modifier.

0
source

All Articles