Paul Lennon
Paul Lennon

Reputation: 77

PHP Handle missing arguments and null values in functions

I want a function to signal error if no parameter is passed. Now it emits a warning but executes the code.

I look into this PHP Error handling missing arguments but I think is more of a question of "empty" casting the input as null or zero.

I'm using:

PHP 5.6.25 (cli) (built: Sep  6 2016 16:37:16)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

I have:

function go($x){
    if(is_null($x))
        print("|nil|"."\n");
    else
        print($x."\n");
}

And getting the expected results as

go(33);
> 33
go("Hello world");
> "Hello World"
go(null);
> |nil|

$in = null;
go($in);
> |nil|
$in = 44;
go($in);
> 44

but if I invoke it without parameters I get

go();
> Warning: Missing argument 1 for go(), called in ...
> |nil|

In this example I'm printing |nil| but in the larger picture it should return the error (or null) to handle some place else.

I've looked into something like

function go($x){
    if(!isset($x)) die("muerto");

    if(is_null($x))
       print("|nil|"."\n");
    else
       print($x."\n");
}

But it kills (dies?:-)) both empty and null cases.

go();
> Warning: Missing argument 1 for go(), called in ...
> muerto

go(null);
> muerto

As usual this is an overly simplified example from a more elaborated code.

Thanks so much for your input.

Upvotes: 3

Views: 2560

Answers (3)

Karol Gasienica
Karol Gasienica

Reputation: 2924

Before using a function you can do something like:

if (isset($x)) { // or can be !empty($x)
    go($x);
} else {
    echo "Error";
{

Or (even better) you can do something like this:

function go($x = null){

In this case a default value of $x is null, so if you will run a function without parameter it will become a null.

So it will be as follows:

function go($x = null){
    if(is_null($x))
        print("|nil|"."\n");
    else
        print($x."\n");
}

About used functions

Default value of function

isset()

empty()

Upvotes: 2

PHPLego
PHPLego

Reputation: 279

You can use default value and func_num_args() function to handle a case when no argument passed. For example:

function go($x = null){
    if(func_num_args() === 0)
        print("error: no argument passed"."\n");
    else if(is_null($x))
        print("|nil|"."\n");
    else
        print($x."\n");
}

Upvotes: 3

Phillip Weber
Phillip Weber

Reputation: 564

Perhaps you can set the param default value to null like so...

function go($x = null){
    if($x == null){
        //handle null value
    }else{
        //do something
    }
}

Upvotes: 1

Related Questions