从PHP函数到文档同时传递回声和字符串?

时间:2012-12-27 23:43:10

标签: php

我有一个与此类似的功能。该函数mysqls并打印新闻。现在,根据mysql结果,这个函数可能会打印或不打印..

function print_div_boxes($mysql)
{
echo 'Print (large sum of) data & divs....';

$printed_already = 1;
}

PHP我希望实现

<?

print_div_boxes($mysql);

if(!$printed_already)
{
print_div_boxes($another_mysql);
}
?>

我只想将$print_already传递给该函数的文档,将其抓取为global或其他任何建议?可能的?

2 个答案:

答案 0 :(得分:1)

编辑完问题后,您根本不需要返回以及对代码进行一些明确的修改,如下所示:

<?php
$printed_already = false;
function print_div_boxes()
{
global $printed_already;
echo 'Print (large sum of) data & divs....';

$printed_already = true;
}
?>

<?php
if(!$printed_already)
{
echo '<div>'; print_div_boxes(); echo '</div>';
}
?>

答案 1 :(得分:1)

这非常简单,您只需要:

确保某个变量(通常是布尔值)表示执行某些函数的结果。这是非常通用的方法。

因此,在程序代码中,它看起来像这样:

<?php

//initial state;
$already_printed = false;


/**
 * instead of using a global keyword, use reference
 * it makes code a bit "clean" 
 */
function print_div_boxes(&$already_printed) //<-- we are passing a reference, not a copy
{
  echo 'Print (large sum of) data & divs....';

  //A couple of thing to note:

  //1) Function Return value SHOULD NOT BE RESULT OF ASSIGNMENT!!!
  //2) No 'return' keyword actually required here, its VOID
  //3) You expect a logic, so use boolean instead of int. It's more appropriate

   $already_printed = true; 
}


//Then use it like:

if ( $already_printed === false ){

   print_div_boxes(&$already_printed);

}