开发者

How to suppress error if an argument is missing in a function call?

I made a function like this (no need to write the whole function here) :

public function selectNode($from, $attributes = null, $childs = null)

and, of course, if I call it this way :

$node->selectNode();

The argument $from isn't initialized and then you got a warning error. I know you can suppress the error doing @$node->selectNode(); or something like that thanks to @.

But, I want to handle it myself. How can I do that if that's possible?

The only way I found is to initialize it like this public function selectNode($from = null, $attributes = null, $childs = null) but that doesn't make it clear ($from is not an option as the others).

(And, of course, t开发者_开发技巧his function, here, is just an example. It could be extended to other functions)


How come you can miss a required parameter? It is not a file or an outside variable! You will get this error just by trying to call this script. It is like parse error. What to handle here? It's development phase error. It just needs to be corrected, not handled.

Anyway, you are doing it wrong.

Never add intentional errors to your code.

Language's error reporting mechanism is for handling unexpected errors, not intentional ones.
If you expect an error here - handle it yourself. Don't make PHP to raise error So, make it $from = null,, yes. And then handle this null whatever you want.


Surely if the $from parameter is not required you should assign it a default variable so it's optional and then do checking based on this.

It would probably be most elegant to just check if $from isset in the code before you reference it and supply it with null as default in the parameters, isset will return false from a null value.


I guess you've got display_errors set to on in php.ini and now these warnings are popping up on your screen and you don't want to see them popping up anymore? If that's the case, then change your php.ini :

display_errors = Off
log_errors = On
error_log = /path/to/php-error.log

Errors will then be logged to the file you specified in error_log, and won't show up on your screen anymore.


You could use a try-catch block handling the error yourself.

try {
  $node->selectNode();
}
catch (Exception $e){
  echo $e; // do whatever you like here with error info $e, if you leave the parenthesis empty here nothing is done and the error message is suppressed
}


Are you looking for the following (or one of its variants)?

<?php error_reporting(0); ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜