OnklMaps
OnklMaps

Reputation: 827

Function argument with no default, do I need to check if defined?

I have a function that requires an argument. My gut tells me to return false if this argument is not set, but do I have to?

function myFun($important) {
    echo "PHP is way too kind";
}

myFun();
@myFun();

Will this ever be echoed? On linux, windows, with some unusual ini-files?

Better safe than sorry and do this?:

function myFun($important) {
    if(!$important) return false;
    echo "PHP is way too kind";
}

Upvotes: 0

Views: 36

Answers (2)

Devon Bessemer
Devon Bessemer

Reputation: 35337

https://3v4l.org/UHbMe

In PHP 7.1 and up, PHP will throw an error. In PHP 7.0 and below, the function will still run and PHP will only emit a warning.

This is just if the argument is not provided. The argument provided could still be a falsey value like NULL, false, 0, or '' without any error or warning being emitted.

Upvotes: 1

Teoman Tıngır
Teoman Tıngır

Reputation: 2901

you can say that, this argument can be null

function myFun($important = null) {
   if(is_null($important)) {
      echo "PHP is way too kind";      
   } else {
      echo $important;
     }
}

or it may have a default value

function myFun($important = "very important") {
   echo $important;
}

Upvotes: 1

Related Questions