Does a simple `return` in a PHP function simply end the function prematurely?

前端 未结 5 1668
梦毁少年i
梦毁少年i 2021-02-14 00:43

I have just seen this

// Check to see if the request is a XHR call    
if (request::is_ajax())
{
  // Send the 403 header
  header(\'HTTP/1.1 403 Forbidden\');
          


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-14 01:37

    Yes, "return;" or return(); in a function stops running that function (or file if the return statement is not in a function) at that point (if the code is executed) and technically returns a null value.

    Your first example would output the 'HTTP/1.1 403 Forbidden' header and then end that function if request::is_ajax() equals true.

    In your code example:

    function text($var) 
    {
    
        if ( ! $var) {
            return;
        }
        do_something();
    
    }
    $var = text('');
    

    You can have the following out comes:

    • If $var is NOT TRUE (i.e. false, null, text or an integer), then exit function and return null.
    • If $var is EXACTLY TRUE (the if statement is checking if $var is anything but true), then run do_something();

    I would suspect you probably want to change the if statement to either:

    if (!is_string($var)) {
    

    if you just want to do_something() to a string or

    if (is_null($var)) {
    

    if you only want to do_something() to $var if it's been set. You may also want to change your function declaration to: function text($var==NULL) { so if you call text without a paramter, $var is automatically set to null.

提交回复
热议问题