Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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 $thisXml;
}
echo $thisXML;

and I only get the xml declaration which is in the variable before the function. If i put an echo in the function, i get everything back as I should.

my page essentially looks like this

$thisXml = 'xml declaration stuff';

function getThisXML($thisXML){
  for(i=1; i<5; i++){
  $query "has the 5 in it";

  while ($mysqlQuery =mysql_fetch_array($theQuery) {
    $thisXml.='add the xml';
  }
  $thisXml.='close the last element';
  return $thisXml;
}

echo $thisXml;

as i said, if I replace the 'return' with 'echo', I get all the nice xml. if I echo outside the function, I only get the original declaration.

really strange, and i've been struggling with this one all day.

like image 492
pedalpete Avatar asked Feb 04 '09 21:02

pedalpete


4 Answers

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;

like image 169
Steerpike Avatar answered Sep 21 '22 23:09

Steerpike


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.

like image 44
jeroen Avatar answered Sep 22 '22 23:09

jeroen


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;
like image 27
mati Avatar answered Sep 19 '22 23:09

mati


You have to call the function and apply echo on the returned value:

 $thisXml = '…';
 echo getThisXML($thisXml);

Or you pass the variably by reference.

like image 29
Gumbo Avatar answered Sep 18 '22 23:09

Gumbo