3

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.

3
  • Did my solution work for you? Commented Nov 4, 2016 at 20:27
  • 1
    I love it when they just "GET and GO", don't you? Commented Nov 4, 2016 at 21:21
  • Yeah.... love it too ;) Commented Nov 5, 2016 at 7:57

3 Answers 3

3

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");
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.