Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 343
Paul Lennon Avatar asked Feb 17 '26 15:02

Paul Lennon


2 Answers

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");
}
like image 123
PHPLego Avatar answered Feb 19 '26 04:02

PHPLego


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()

like image 30
Karol Gasienica Avatar answered Feb 19 '26 04:02

Karol Gasienica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!