2016-10-19 5 views
0

ここからわかりますように、私は自分のコード全体でいくつかの変数を宣言しています。私はそれ以外の部分を切り捨てましたが、上記の変数を参照するためにグローバルを使用していることがわかります。私の割り当てでは、グローバル変数を使わないようにする必要があり、グローバル変数を置き換えてもまだその変数を使用できる潜在的な解決策を見つけるために、インターウェブをスカウトすることはできません。何か案は?グローバル変数を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")); 
関連する問題