Jump to content

A couple questions on OOP


AzizLight

Recommended Posts

Hi everybody,

There are some stuff about OOP that are not clear for me:

 

1- when I declare a class, and create a constructor with several optional parameters as such:

 

class FooBar{
   public $foo, $bar, $foobar;

   public function __construct($foo, $bar=null, $foobar=null){ ... }
}

 

If I then want to create an instance of that object with $foo and $foobar as parameters ($foo being madatory, $foobar being one of the optional parameters), how would I proceed?

The only way that I see is creating it as such:

 

$foobar1 = new FooBar(1, null, 3);

 

but if I have 30 optional parameters and I want to create an instance of the object with only one of the optional parameters I will have to type null 29 times and put the value of the wanted optional parameter at the right place?

Not convenient, so how should I proceed?

 

2- When I create a class Foo:

 

class  Foo{
   public $foo;

   public function __construct($foo){ ... }    
}

 

and a another class bar that extends foo:

 

class  Bar{
   public $bar;

   public function __construct($bar){ ... }    
}

 

Is this the correct synthax for the Bar class? Or should it be something like that:

 

class  Bar{
   public $bar;

   public function __construct($foo, $bar){ ... }    
}

Link to comment
Share on other sites

Thanks for your answer. I forgot the keyword 'extends' indeed, that was a mistake of me. But what I wasn't sure was the synthax of the constructor of the child class. I wasn't sure if I had to repeat the parameters or not. The answer is: yes and no. It depends what I actually want. If I want the Bar class to have two parameters then I have to include all the parameters. So the correct synthax would be the second one.

 

For the first question, the "logical" synthax I provided is the correct one too. In the case of a class with a constructor that has 30 parameters, I figured that either the class is very poorly writter or the level of the code is so high that by the time I write a class with a constructor that takes 30 parameters I'll know how to manage it :P

 

So after asking questions in the Freenode ##php irc channel and researching and testing (and...that's it :P) I managed to answer my own questions :)

 

Anyway, thanks again for you answer

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...