Forum Moderators: coopster

Message Too Old, No Replies

Which one is better & why ?

         

PHPycho

8:43 am on Mar 27, 2008 (gmt 0)

10+ Year Member



Hello forums !
I would like to know a few things about OOP.
Which one is better ?
1> [PHP]class A{
var $a;
var $b;
function A(){
$this->a = array();
$this->b = 10;
}
}[/PHP]
2>
[PHP]class A{
var $a = array();
var $b = 10;
function A(){

}
}[/PHP]

In both cases there is initialization of default values in properties.
I would like to know which one is better to initialize the default values and why ?

Thanks in advance for the Suggestion.

PHP_Chimp

9:35 pm on Mar 27, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I dont know if this really answers your question but I will throw it in anyway.

As I work with a lot of different groups of programmers some use your first method, others use your second method. I have never noticed a difference in either method, although I have not specifically checked execution time.
The examples in the manual actually use both methods. From the php4 manual -

/* This is how it should be done. */
class Cart {
var $todays_date;
var $name;
var $owner;
var $items = array("VCR", "TV");

function Cart() {
$this->todays_date = date("Y-m-d");
$this->name = $GLOBALS['firstname'];
/* etc. . . */
}
}


However I tend to stick with a single method when I'm coding, just so that I know where I have initialized each of the variables. What method just depends on who I'm coding for.

coopster

10:06 pm on Mar 27, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



If you are not going to use anything other than a constant expression for the default value then you can use the second method. However, if you ever want to initialize those variables with something other than a constant expression like a variable, a class member, a function call, etc. you will need to update your code to the method shown in the first example and the one quoted from the PHP manual page by PHP_Chimp.