2014-06-23 3 views
1

일부 코드를 리팩터링하려고하고 있으며 전역 변수를 사용하는 템플릿이 있습니다. requireinclude 함수의 내부는 로컬 범위 만 사용하므로 "글로벌 필요"가 있습니까?전역 변수를 사용하는 템플릿이 필요한 PHP

지금 우리는 이와 같은 모든 라우터 파일에 걸쳐 상당 수의 코드를 복제했습니다. 이 문제와 관련된 문구는 다음과 같습니다.

require 'header.php'; 
require $template; 
require 'footer.php'; 

이러한 진술은 전역 범위에 있습니다. 이 같은 클래스 내부의 방법으로 이러한 리팩토링하기 위해 노력하고있어 :

class Foo { 

    /** 
    * Template file path 
    * @var string 
    */ 
    protected $template; 

    public function outputHTMLTemplate() { 
     header("Content-Type: text/html; charset=utf-8"); 
     require 'header.php'; 
     if (file_exists($this->template)) { 
      require $this->template; 
     } 
     require 'footer.php'; 
    } 

} 

내가 template.php이 템플릿 내에서 자동 전역 및 전역 변수는 다음과 같이 존재한다고 가정 :

<h1>Hello <?= $_SESSION['username']; ?></h1> 
<ul> 
<?php 
foreach ($globalVariable1 as $item) { 
    echo "<li>$item</li>"; 
} 
?> 
</ul> 

이가이다 단순화 된 예제에서 실제 템플릿에는 꽤 많은 전역 변수가있을 수 있습니다.

출력 코드를 메서드로 이동하려면 어떻게해야합니까?

답변

0

extract PHP 함수를 사용해 볼 수 있습니다. 글로벌 범위에 포함 된 것처럼 모든 글로벌 변수를 포함 된 파일에 사용할 수있게합니다.

<?php 

$myGlobal = "test"; 

class Foo { 

    /** 
    * Template file path 
    * @var string 
    */ 
    protected $template; 

    public function outputHTMLTemplate() { 
     extract($GLOBALS); 

     header("Content-Type: text/html; charset=utf-8"); 
     require 'header.php'; 
     if (file_exists($this->template)) { 
      echo $myGlobal; // Prints "test" 
      require $this->template; 
     } 
     require 'footer.php'; 
    } 

} 

$x = new Foo(); 
$x->outputHTMLTemplate(); 
0

슈퍼 전역이 이미 제공됩니다. 다른 변수의 경우는 약간의 추가 작업하지만 정상적인 방법은 무엇인가 같은 것 : 글로벌 변수의 수는 런타임시 다를 수 있으므로

protected $data; 
protected $template; 

public function outputHTMLTemplate() { 
    header("Content-Type: text/html; charset=utf-8"); 
    require 'header.php'; 
    if (file_exists($this->template)) { 
     extract($this->data); 
     require $this->template; 
    } 
    require 'footer.php'; 
} 

public function setData($var, $val) { 
    $this->data[$var] = $val; 
} 

$foo->setData('globalVariable1', $globalVariable1); 
+0

이 가능하지 않습니다. '$ GLOBALS'을 사용 하시겠습니까? (예 :'public function __construct() {$ this-> data = $ GLOBALS;}')? –

+0

매우 안전하지는 않지만 그렇습니다. @ Christian의 대답을보십시오. – AbraCadaver

관련 문제