php自訂函數如何引用外部變數?

來源:互聯網
上載者:User
在寫到評論的迴圈嵌套的時候遇到一個問題:
Warning: Invalid argument supplied for foreach() in /home/yiliaoba/domains/chaochaoblog.com/public_html/wp-content/themes/chaochao/comments.php on line 49
好了,出現了一個invalid argument,即一個停用參數。

這個問題是怎麼產生的呢,回去找找代碼如下:
foreach ($comments as $comment) :

這下就看出來了,$comments 是函數外的變數,而我們就在函數中使用了。按照一般程式編寫的思路,函數外的變數應該是可以看成全域變數的,如果是全域變數的話,那麼在函數中調用是完全沒有問題的。

看來php和我們傳統的思路有點問題,那麼php中全域變數是怎麼的呢,我特意編寫代碼試試看。

1.在外部用global定義直接輸出:

global $mytext;$mytext=”nihao”;function chao_echo(){echo $mytext;}chao_echo();

結果:沒有輸出;

2.用GLOBALS數組輸出:

global $mytext;$mytext=”nihao”;function chao_echo(){echo $GLOBALS['mytext'];}chao_echo();

結果:輸出正常

3.在函數內全域申明函數外的變數:

$mytext=”nihao”;function chao_echo(){global $mytext;echo $mytext;echo $GLOBALS['mytext'];}chao_echo();

結果:直接輸出或者用GLOBALS全域數組輸出都行。
4.將函數外部變數用參數傳遞進去:

$mytext=”nihao”;function chao_echo($mytext){echo $mytext;}chao_echo($mytext);

結果:可以輸出。

總結一下,php中,函數內引用函數外的變數三種方法:

1.函數外global聲明,函數內使用$_GLOBALS數組引用。

2.函數內global聲明,函數內$_GLOBALS數組或者直接引用。

3.在調用函數的時候用一個參數傳遞。
那麼,我們修改版的迴圈嵌套的函數如下

<?php function chao_comment_circle($chao_id,$comments){?><?php foreach ($comments as $comment)  ><?php if($comment->comment_parent==$chao_id)  >    <!-- 子評論 b -->    <div class="comment_one_sub">    <?php if (function_exists('get_avatar')) { ?> <div class="gravatar_sub"><?php echo get_avatar($comment->comment_author_email,'32'); ?></div> <?php } ?>    <div class="comment_frame_sub">     <div class="comment_author_sub"><a href="<?php echo $comment->comment_author_url; ?>"><?php echo $comment->comment_author; ?></a></div>      <div class="comment_reply_sub" onclick="chao_reply('<?php echo $comment->comment_ID; ?>','<?php echo $comment->comment_author; ?>')"><a href="#respond">【回複】</a></div>       <div class="comment_date_sub"><?php echo $comment->comment_date; ?>  <?php echo $comment->comment_time; ?></div></div><div class="comment_text_sub"><?php echo $comment->comment_content; ?></div><?php chao_comment_circle($comment->comment_ID,$comments); ?></div><!-- 子評論 e --><?php endif ?><?php endforeach ?><?php}?>

$chao_id是我們母評論的ID,即我們因該先輸出不是回複的評論,在其末尾調用該回複輸出函數。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.