2013-07-29 82 views
1

我试图从数组中打印数据。该数组来自一个类。我越来越从类php打印数组

array(0) { } 

代替:

Array ([0] => header_index.php [1] => footer.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(); 
?> 

什么,我做错了什么?在此先感谢

+0

'get_object_vars()'返回一个对象的public __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()调用返回。变量只存在于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()); 

注意拨打get_object_vars()你仍然会得到一个空数组,因为我所做的$template_config变量private,迫使调用者使用getTemplate()方法来访问模板数据。

0

它看起来像你没有初始化$ templateconfig变量,直到getTemplate()被调用。直到var_dump()之后才能调用它。

所以基本上,你倾销一个没有initalized成员属性的对象,这就是为什么你看到一个空数组。