echo函数里面的函数bug

时间:2014-02-26 04:53:40

标签: php html function

我有以下PHP代码:

function button1($attr, $text) {
  $data = "<button ";

  foreach($attr as $names => $specs) {
    $data .= $names . "='" . $specs . "' ";
  }

  $data .= ">" . $text . "</button>\n";
  echo $data;
}

function span1($attr, $text) {
  $data = "<span ";

  foreach($attr as $names => $specs) {
    $data .= $names . "='" . $specs . "' ";
  }

  $data .= ">" . $text . "</span>\n";
  echo $data;
}

button1(
  array( "type" => "button",
         "class" => "navbar-toggle",
         "data-toggle" => "collapse",
         "data-target" => ".navbar-collapse"
  ),
  span1(
    array( "class" => "sr-only" ),
    "Toggle navigation"
  )
);

从上面的代码中,我希望结果如下所示:

<button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse' >
  <span class='sr-only' >Toggle navigation</span>
</button>

但它看起来像这样:

<span class='sr-only' >Toggle navigation</span>
<button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse' ></button>

我必须做些什么才能得到我想要的结果?谢谢你的帮助。

3 个答案:

答案 0 :(得分:2)

简单,从不 echo来自各种功能。问题是,首先评估span1(),导致其echo执行。它也不返回任何用作button1() $text参数的内容。然后执行button1() echo,将其内容打印到输出流 span1()回显之后。

将每个功能的最后一行更改为

return $data;

并通过

执行
echo button1(...);

答案 1 :(得分:0)

用这个替换你的PHP代码, 您必须return $data进入函数并回显button1();

<?php 

function button1($attr, $text) {
  $data = "<button ";

  foreach($attr as $names => $specs) {
    $data .= $names . "='" . $specs . "' ";
}

  $data .= ">" . $text . "</button>\n";
return $data;
}

function span1($attr, $text) {
  $data = "<span ";

  foreach($attr as $names => $specs) {
    $data .= $names . "='" . $specs . "' ";
  }

  $data .= ">" . $text . "</span>\n";
  return $data;
}

echo button1(
  array( "type" => "button",
         "class" => "navbar-toggle",
         "data-toggle" => "collapse",
         "data-target" => ".navbar-collapse" ),
  span1(
    array( "class" => "sr-only" ),
    "Toggle navigation"
  )
);

答案 2 :(得分:0)

您好在下面的代码中使用您想要的输出     function button1($ attr,$ text)     {         $ data =&#34;

    foreach($attr as $names => $specs) 
    {
         $data .= $names . "='" . $specs . "' ";
    }

    $data .= ">" . $text . "</button>\n";
    return $data;
}

function span1($attr, $text) 
{
     $data = "<span ";

     foreach($attr as $names => $specs) 
     {
          $data .= $names . "='" . $specs . "' ";
     }

     $data .= ">" . $text . "</span>\n";
     return $data;
}

$str = span1(
         array( "class" => "sr-only" ),
                "Toggle navigation"
        );

echo button1(           数组(&#34;类型&#34; =&gt;&#34;按钮&#34;,                  &#34;类&#34; =&GT; &#34;导航栏肘节&#34 ;,                  &#34;数据肘节&#34; =&GT; &#34;崩&#34 ;,                  &#34;数据目标&#34; =&GT; &#34; .navbar合拢&#34;                 )                  $海峡     );