从php中的函数返回变量(返回不工作)

问题描述 投票:7回答:7

我正在一个函数内部构建一个XML页面,由于一些奇怪的原因,我没有把整个东西吐出函数。我试过了

return $thisXml;
}
echo $thisXML;

我只获得函数前变量中的xml声明。如果我在函数中放置一个回声,我会尽可能地回复所有内容。

我的页面基本上是这样的

$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;

正如我所说,如果我用'echo'替换'return',我会得到所有不错的xml。如果我在函数外回声,我只得到原始声明。

真的很奇怪,我整天都在为这一天苦苦挣扎。

php
7个回答
10
投票
return $thisXml;
}
echo $thisXML;

$ thisXML;仅存在于函数的范围内。要么$ thisXML;全局(坏主意)或echo getThisXML(),其中getThisXML是返回$thisXML的函数;


7
投票

你实际上是在调用这个函数:

$thisXml = getThisXML($someinput);

也许是一个愚蠢的问题,但我在你的描述中没有看到它。


2
投票

您必须调用该函数并在返回值上应用echo

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

或者你通过reference可变地传递。


2
投票

你需要调用这个功能!

$thisXml = 'xml declaration stuff';

echo getThisXML($thisXML);

或者通过引用传递变量:

$thisXml = 'xml declaration stuff';

function getThisXML(&$thisXML){
  ...
  return $thisXml;
}

getThisXML($thisXML);
echo $thisXml;

1
投票

您正在尝试使用函数范围内定义的变量。

使用:

$thisXML;

function do(){
 global $thisXML;
 $thisXML = "foobar";
}

print $thisXML;

1
投票

返回一个变量并不意味着它会全局影响该变量,这意味着函数调用将计算到它所使用的值。

$my_var = 5;

function my_func() {
  $my_var = 10;
  return $my_var;
}

print my_func();
print "\n";
print $my_var;

这将打印

10
5

0
投票
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;
?>
© www.soinside.com 2019 - 2024. All rights reserved.