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