views:

80

answers:

6

Hay, when should variables be set within a PHP class?

<?php
    class MyClass {
        var $my_var;    // here? like var $my_var = null;
        function __construct(){
            $this->my_var = null; // or here?
        }
    }
?>
+3  A: 

It depends what you want to initialise them to. I prefer to initialise them when they're declared if possible, but if they need to be, for example, the result of a method call, then you'll need to initialise them in the constructor.

Greg
So it does not really matter? Either way i want all my variables to be set to null upon creating an instance of the object.
dotty
No it doesn't matter. Just ensure you have them initialized before you intend to use them.
James
If you want them set to null then just var $my_var; will do (though you should be using e.g. public $my_var; for PHP5)
Greg
Cheers greg. You've been a big help :)
dotty
A: 

i'd say

 class Foo 
 {
  public $bar = 'default';

  function __construct($custom_bar = null) {
   if(!is_null($custom_bar))
    $this->bar = $custom_bar;
  }
stereofrog
+1  A: 

I'm thinking it would be best to initialize them in the constructor. I would normally think it's a matter of developer preference, but with the introduction of auto-implemented properties with C# 3.0, I think it makes more sense to simply put all intialization in the constructor(s) because you cannot supply a value to a property declared in this manner. And being consistent about where you intialize variables makes your code more readable.

Mayo
Not *entirely* sure how C# 3.0 affects PHP...
Greg
Well that's certainly funny... figured it was .NET. I see everything as pseudo code these days I guess.
Mayo
+1  A: 

Depends on the usage of the variable. OOP has always tried to emphasize that you initialize your variables in the contructor of the class.

James
A: 

As soon as you have enough info to set them correctly.

Visage
A: 

To me, a variable initialized at its declaration (outside of the constructor) looks too much like a constant. It's totally preference, but I choose to initialize in the constructor if at all possible.

Tenner