luqita
luqita

Reputation: 4077

PHP: Obligatory params

What would be the best way, when it comes to practices, to return false if some param is not passed to a PHP function?

Mainly because I am calling this function will be called with params that come from the frotend, which means that the user could pass null as a param, and I want to return false if that happens.

At the top of the function I put:

if (empty($param1) || empty($param2) || empty ($param3)) {
            return false;
        }

Any better ways of doing this?

Upvotes: 1

Views: 120

Answers (6)

mobius
mobius

Reputation: 5174

Just for fun:

function test() {
  if( count(array_filter(func_get_args(), create_function('$v', 'return isset($v);'))) ) {
    throw new \InvalidArgumentException("Invalid parameters");
  }
}

Upvotes: 2

QuantumRob
QuantumRob

Reputation: 2924

You can handle the way you are handling it, or you can specify default values for the function. Many PHP calls handle optional parameters this way.

function($param1, $param2='default',$param3='default')

This way you can ensure your code has the right values every time or at least "sane" ones regardless of what you are passed.

You can raise an exception in your code as well.

Upvotes: 0

Eugene
Eugene

Reputation: 3375

I prefer this way:

function a($param1 = null, $param2 = null) {
    if(!isset($param1, $param2)
        return false;
}

Upvotes: -1

Molochdaa
Molochdaa

Reputation: 2218

Beware : empty(0) will return false.

maybe isset() is better for your case.

Upvotes: 1

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14941

We have the SPL InvalidArgumentException Exception for that.

Upvotes: 2

KingCrunch
KingCrunch

Reputation: 131841

In short: Exception. We are in 2011 now, false in case of errors is discouraged.

However, I would not test with empty(), because this covers '' (empty string of course) and 0 too. That is probably not wanted in every case.

Upvotes: 5

Related Questions