When declaring an array as a class member, which way should it be done?
class Test1 { private $paths = array(); public function __construct() { // some code here } }
or
class Test2 { private $paths; public function __construct() { $this->paths = array(); // some code here } }
Which one is better in terms of good practices and performance? What would you recommend?
In PHP, the array() function is used to create an array: array(); In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index.
An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
I'd suggest doing this when declaring a class variable. A constructor can be overriden in extending classes, which might result in E_NOTICEs or even E_WARNINGs if any of your functions depend on this variable being an array (even an empty one)
If you are going to populate your array dynamically during initialization, do it in the constructor. If it contains fixed values, do it in the property declaration.
Trying to populate an array dynamically (e.g. by using the return value of a certain function or method) within the declaration results in a parse error:
// Function call is not valid here private $paths = get_paths();
Performance is not a real concern here as each has its own use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With