Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP5. Two ways of declaring an array as a class member [closed]

Tags:

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?

like image 616
ezpresso Avatar asked Dec 29 '10 20:12

ezpresso


People also ask

How can you declare the array in PHP?

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.

How an array is declared in PHP explain with example?

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.


2 Answers

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)

like image 178
Mchl Avatar answered Oct 22 '22 03:10

Mchl


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.

like image 29
BoltClock Avatar answered Oct 22 '22 03:10

BoltClock