Returning a variable from a function in php (return not working)

后端 未结 7 2030
旧时难觅i
旧时难觅i 2021-01-02 18:46

I\'m building an XML page inside of a function, and for some strange reason I don\'t get the whole thing spit out of the function. I\'ve tried

return $thisX         


        
相关标签:
7条回答
  • 2021-01-02 19:07

    Are you actually calling the function in the sense of:

    $thisXml = getThisXML($someinput);
    

    Maybe a silly question, but I don´t see it in your description.

    0 讨论(0)
  • 2021-01-02 19:07

    You need to invoke the function!

    $thisXml = 'xml declaration stuff';
    
    echo getThisXML($thisXML);
    

    Or pass the variable by reference:

    $thisXml = 'xml declaration stuff';
    
    function getThisXML(&$thisXML){
      ...
      return $thisXml;
    }
    
    getThisXML($thisXML);
    echo $thisXml;
    
    0 讨论(0)
  • 2021-01-02 19:09
    You can create function in php this way:
    
    <?php
    
    $name = array("ghp", "hamid", "amin", "Linux");
    function find()
    {
        $find = 0;
        if(in_array('hamid', $name))
        {
          $find = 1;
          return $find;
        }
        else 
        {
          return $find;
        }
    }
    
    
    //###################
    $answare = find();
    echo $answare;
    ?>
    
    0 讨论(0)
  • 2021-01-02 19:10

    You are trying to use a variable defined inside the function scope.

    Use:

    $thisXML;
    
    function do(){
     global $thisXML;
     $thisXML = "foobar";
    }
    
    print $thisXML;
    
    0 讨论(0)
  • 2021-01-02 19:12
    return $thisXml;
    }
    echo $thisXML;
    

    $thisXML; only exists in the scope of the function. Either make $thisXML; global (bad idea) or echo getThisXML() where getThisXML is the function that returns $thisXML;

    0 讨论(0)
  • 2021-01-02 19:14

    Returning a variable doesn't mean that it affects that variable globally, it means the function call evaluates to that value where it's used.

    $my_var = 5;
    
    function my_func() {
      $my_var = 10;
      return $my_var;
    }
    
    print my_func();
    print "\n";
    print $my_var;
    

    This will print

    10
    5
    
    0 讨论(0)
提交回复
热议问题