2016-10-19 86 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"));