Which one is better & why ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

Which one is better & why ?

Post by PHPycho »

~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


Hello forums !!
I would like to know a few things about OOP.
Which one is better ?
1>

Code: Select all

class A{
            var $a;
            var $b;
            function A(){
                $this->a = array();
                $this->b = 10;
            }
        }
2>

Code: Select all

class A{
            var $a = array();
            var $b = 10;
            function A(){
                
            }
        }

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.


~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Which one is better & why ?

Post by onion2k »

They're different, neither is 'better'. The first one makes the default values class specific, while the second makes them superclass specific. That is to say, if you wrote a new class that extends A using the first way of creating the default values the new class would only have thosee defaults if you didn't write a new constructor for it. If you used the second way the new class would have those defaults even if it had a new constructor.

But.. personally, I tend to do:

Code: Select all

class A{
  var $a;
  var $b;
  function A($a=array(), $b=10){
    $this->a = $a;
    $this->b = $b;
  }
}
That way I can override them easily, and a constructor for an extension can still change them too.
User avatar
mchaggis
Forum Contributor
Posts: 150
Joined: Mon Mar 24, 2003 10:31 am
Location: UK

Re: Which one is better & why ?

Post by mchaggis »

I would generally opt for the following hybrid:

Code: Select all

 
class A{
   var $a=array();
   var $b=0;
   function A($a=array(), $b=10){
     $this->a = $a;
     $this->b = $b;
   }
}
The reason is that I occaisionally have reasons to call the methods of a class in the $A::method() format instead of $A->method() and unless $a is defined then $a is not an array.
(Hope that makes sense)

It's nice to specify, but not necessary.
Post Reply