Php function argument error suppression, empty() isset() emulation

后端 未结 14 716
执笔经年
执笔经年 2021-01-11 17:32

I\'m pretty sure the answer to this question is no, but in case there\'s some PHP guru

is it possible to write a function in a way where invalid arguments or non exi

14条回答
  •  情深已故
    2021-01-11 18:19

    There are valid cases where checking becomes cumbersome and unnessesary.
    Therfore i've written this little magic function:

    /**
     * Shortcut for getting a value from a possibly unset variable.
     * Normal:
     *   if (isset($_GET['foo']) && $_GET['foo'] == 'bar') {
     * Short:
     *   if (value($_GET['foo']) == 'bar') {
     *
     * @param mixed  $variable 
     * @return mixed  Returns null if not set
     */
    function value(&$variable) {
        if (isset($variable)) {
            return $variable;
        }
    }
    

    It doesn't require any changes to myHappyFunction().
    You'll have to change

    myHappyFunction($someBogusVar);
    

    to

    myHappyFunction(value($someBogusVar));
    

    Stating your intent explicitly. which makes it good practice in my book.

提交回复
热议问题