2013-07-29 4 views
1

배열에서 데이터를 인쇄하려고합니다. 배열은 클래스에서 온 것입니다. 내가 잘못클래스 PHP에서 배열 인쇄

<?php 
class TemplateModel { 
    public function getTemplate($template = "index"){ 
     switch($template){ 
      case "index": 
       $templateconfig = array("header_index.php","footer.php"); 
       break; 
     } 
     return $templateconfig; 
    } 
} 
$temodel = new TemplateModel(); 
var_dump(get_object_vars($temodel)); 
$temodel -> getTemplate(); 
?> 

을하고 있어요 무엇 :

Array ([0] => header_index.php [1] => footer.php) 

코드는 다음과 같습니다 나는

array(0) { } 

대신

받고 있어요? 감사합니다 사전에

+0

'get_object_vars()'는 객체의 공개 __properties__를 반환합니다. 해당 메서드에 사용 된 로컬 변수가 아닙니다. –

답변

1
var_dump(get_object_vars($temodel)); 

은 클래스 구성원 $temodel을 출력합니다. 클래스 멤버 변수가 없으므로 출력이 비어 있습니다. 당신은 출력 배열을 원하는 경우에, 당신은 예를 들어,이 작업을 수행 할 수 있습니다 자체가 어떤 변수 (속성)이 없습니다

print_r($temodel -> getTemplate()); 
+0

덕분에 많은 도움이되었습니다. –

0

'getTemplate'함수에서 변수를 설정하고 var_dump 이후까지 호출되지 않는 것처럼 보입니다.

ADD : 그리고 나는 당신이 그 기능의 복귀를 포착하지 않는 것을 눈치 채 셨습니다. 클래스에서 생성 된 객체를 var_dumping하고 있습니다.

FIX :

<?php 
class TemplateModel { 
    public function getTemplate($template = "index"){ 
     switch($template){ 
      case "index": 
       $templateconfig = array("header_index.php","footer.php"); 
       break; 
     } 
     return $templateconfig; 
    } 
} 
$temodel = new TemplateModel(); 
$returned_var = $temodel -> getTemplate(); 
var_dump($returned_var); 
?> 

당신이 객체의 변수로 배열을 설정하려면, 즉 다른 문제입니다.

0

개체가 get_object_vars()에 대한 호출로 반환 될 수 있습니다. $templateconfig 변수는 getTemplate() 함수의 범위 내에 만 존재하며 객체의 속성이 아닙니다.

의도가 그것에게 개체의 속성을 확인하는 것입니다, 당신은 다음과 같이해야한다 : 여기

class TemplateModel { 
    private $template_config = array(
     'index' => array("header_index.php","footer.php"), 
     // add other configs here 
    ); 

    public function getTemplate($template = "index"){ 
     if(empty($template)) { 
      throw new Exception('No value specified for $template'); 
     } else if (!isset($this->template_config[$template])) { 
      throw new Exception('Invalid value specified for $template'); 
     } 

     return $this->template_config[$template]; 
    } 
} 

$temodel = new TemplateModel(); 
var_dump($temodel->getTemplate()); 

참고 내가 $template_config 만든 것처럼 여전히 빈 상태 (empty)의 배열을 얻을 것 get_object_vars() 호출하는 경우를 변수 private을 사용하여 호출자가 getTemplate() 메서드를 사용하여 템플릿 데이터에 액세스하도록합니다.

0

getTemplate()이 호출 될 때까지 $ templateconfig 변수를 초기화하지 않은 것처럼 보입니다. var_dump()가 끝날 때까지 호출하지 마십시오.

기본적으로 빈 멤버 배열이없는 멤버 속성이없는 개체를 덤프하고 있습니다.