0

Why do we need declare $slug argument as default NULL in the function? What will change if we won't declare it default NULL?

It looks for me like nothing would change:

public function view($slug = NULL)
{
    $data['news_item'] = $this->news_model->get_news($slug);

    if (empty($data['news_item']))
    {
        show_404();
    }
    ...
Blauharley
  • 4,186
  • 6
  • 28
  • 47
  • The difference is when you call the function. If a default is set, you can call it with no args e.g. `$ob->view();`, if there isn't a default set, then that will error, as you are required to pass a value e.g. `$ob->view('somevaluehere');` – Jonnix Jan 04 '18 at 14:08

3 Answers3

1

You have the option of setting a default value (NULL in your case), which then makes that argument optional, rather than required. That is why it looks to you like it is unnecessary, you probably only call this function with an argument.

You can look this up here.

creyD
  • 1,972
  • 3
  • 26
  • 55
tbedner
  • 323
  • 1
  • 10
0

To make the parameter optional.

When creating functions in PHP it is possible to provide default parameters so that when a parameter is not passed to the function it is still available within the function with a pre-defined value. These default values can also be called optional parameters because they don't need to be passed to the function.

Let's say u have a function like that;

function testFunction($a = 1)
{
    return $a;
}
// When u call it
echo testFunction(); // prints 1
echo testFunction(2); // prints 2
htunc
  • 455
  • 5
  • 19
0

No default parameter:

When you write a funktion with this header

public function view($slug)

You HAVE TO hand over a parameter when you call this function. Otherwise this will throw an Error.

Default parameter:

public function view($slug = NULL)

With this header you can but not have to hand over a parameter.

Melody
  • 182
  • 2
  • 12