2016-10-19 84 views
0

因此,您可以在這裏看到我已經聲明瞭我在整個代碼中使用的幾個變量。我將其餘部分刪除,但有些情況下您會看到我使用global來引用上述變量。我的任務要求我們不要使用全局變量,並且似乎無法偵測到interwebs找到任何可能的解決方案來替換global,但仍然能夠使用所述變量。有任何想法嗎?替換php中的全局變量

//variables 
$movie = $_GET["film"]; //dynamically get film name via link 
$contents = file_get_contents("$movie/info.txt"); //get info of said film from /info file in my docs (name, rating, year) 
$info = explode("\n",$contents); 
$sidecontents = file_get_contents("$movie/overview.txt"); //get all the credits (producer, ratings, etc) of film that is displayed below image 
$b = explode("\n",$sidecontents); //for every new line (in the txt they're in same line but theres the line break), split each string by string 
$j = 0; //variable to use as a counter 

//rotten or fresh icon next to rating for movie 
function percentLogo($inf) 
{ 
    //if percentage of film is more than 60 then print fresh tomato 
    if($inf >= 60) 
    { 
     ?> <img src='freshbig.png' alt='Fresh'/> 
     <?php 
    } 
    //else, rotten tomato lol self explanatory but yeah 
    else 
    { 
     ?> <img src='rottenbig.png' alt='Rotten'/> 
<?php 
    } 
} 
//info on the right sidebar of the page (not including the picture) 
function sideinfo() 
{ 
    global $b; 
    foreach($b as $credits) //for each loop to increment through b (which is all the content we split for each line break) and store it in credits dynamically. 
    { 
     $credits = explode(":",$credits); //we then split the string up for everytime we see a : and store it in credits again (bad programming practice but it's late so whatever lol) 
     //essentially print out wh 
+0

您可以在函數中使用'$ _GET'。另外,你可以將其他人傳遞給函數。你瞭解函數參數嗎? – AbraCadaver

+0

我不確定其他的PHP開發者。但我不認爲使用全局變量是好的。我相信他們是不好的做法和魔術變數的標誌。我鼓勵人們使用另一種方法。使用一個類,而不是更好 – Tim

+0

謝謝@Tim這是(我假設)他們爲什麼要求另一種方法。 – AbraCadaver

回答

0

雖然這是一項任務,我不會爲你做這項工作。然而,向正確的方向推動通常會訣竅。測試的想法是如何恰當地使用功能。

function getMovieInfo(){ 
    $contents = file_get_contents($_GET["film"] . "/info.txt"); 
    # This variable is defined in a function, it is a local variable and not global. 

    return explode("\n",$contents); 
} 

print_r(getMovieInfo()); 

不是將值存儲在變量中,而是返回它。 在這種情況下,您返回一個數組,但您可以處理該函數中的信息以返回特定的內容。

使用函數的參數,你可以讓它多了幾分動感:

function getMovieInfo($file){ 
    return explode("\n",file_get_contents("$file/info.txt")); 
    # -------------------------------------^ nameofmovie/info.txt 
} 

print_r(getMovieInfo("nameofmovie"));