[請益] 透過 functon include 檔案,裡面的變數

看板PHP作者 (陸奧鬼一)時間15年前 (2009/10/16 20:18), 編輯推噓4(406)
留言10則, 2人參與, 最新討論串1/1
aaa.html: this is aaa.html...<?php echo $a;?>... aaa.php: $a = 'this is var:a'; func_xxx('aaa.html'); // 寫法1 include(func_yyy('aaa.html')); // 寫法2 function func_xxx($v) { include ('/filepath/' .$v); } function func_yyy($v) { return '/filepath/' . $v; } 寫法1,確實有 include aaa.html,不過 $a,因為 scope 的關係,不會有值。 目前想到的解法是用寫法2,$a 可以正確的印出。 想請問版上的高手,在不考慮 smarty 或其它套件的條件下, 有沒有其它方法可以在 aaa.php 透過 function include aaa.html, 而且 aaa.html 裡的變數也可以正確的印出? 謝謝!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.136.106.128 ※ 編輯: s5846125 來自: 220.136.106.128 (10/16 20:20)

10/16 20:23, , 1F
少了global $a;
10/16 20:23, 1F

10/16 20:23, , 2F
變數範圍的觀念
10/16 20:23, 2F

10/16 20:27, , 3F
謝謝,我知道$a,因為 scope 的關係,不會有值。
10/16 20:27, 3F

10/16 20:31, , 4F
加上global即可
10/16 20:31, 4F

10/16 20:37, , 5F
謝謝a大,實際運作的時候會有很多個變數。
10/16 20:37, 5F

10/16 20:40, , 6F
可以跑迴圈把所有變數global,參考我之前的文章
10/16 20:40, 6F

10/16 20:41, , 7F
#1AnRUtYn 有中間有這樣的技巧
10/16 20:41, 7F

10/16 21:09, , 8F
感謝a大提供的方法,不過要注意一個地方,因為 func_xxx
10/16 21:09, 8F

10/16 21:10, , 9F
有傳入參數,在foreach{}裡的global $$v;會讓參數值消失。
10/16 21:10, 9F

10/16 21:15, , 10F
你可以把他單獨排除在外
10/16 21:15, 10F
文章代碼(AID): #1As6IUFr (PHP)