为什么我的变量为null?

时间:2011-06-07 12:47:14

标签: php arrays codeigniter drop-down-menu

我目前正在编辑一个有PHP经验的工作项目。

我对基础知识有点了解,但我对MVC和Code-Igniter知之甚少,所以当然我会遇到一些问题。

我的第一个问题是我正在尝试从控制器填充下拉列表。

该视图名为“overview_screen.php”,控制器名为“overview.php”。

在控制器中我有一个功能:

private function getYears()
{
    return array('Test1', 'Test2', 'Test3', 'Test4');
}

我在索引中设置为$ years:

function index()
{
    $years = $this->getYears();             
    $menu = $this->getMenu();       
}           

当我在$菜单上执行var_dump时,它会显示菜单,因为它应该显示但是当我在$ $上执行var_dump时它会说:

PHP Error was encountered   
Severity: Notice    
Message: Undefined variable: years    
Filename: views/overview_screen.php    
Line Number: 92

任何人都知道为什么会这样/不起作用?

[编辑]

添加信息:

<?php
print_r(CI_session::userdata('docent_id'));

if (!$this->session->userdata('docent_id')) {
    header ('Location: /bpv-registratie/welcome.html');
}
?>

<html>
<head>
<title>Registratie Systeem</title>

</head>
<body>

<div id="topmenu">
    <a href="/registratie/" class="button">Start</a>
    <a href="/registratie/welcome/logout.html" class="button">Log uit</a>       
</div>

<div id="topmenuright">
<?php var_dump($years); ?>
    <select>        
        <?php foreach ($years as $row):?>
            <option><?=$row?></option>
        <?php endforeach;?>
    </select>
</div>

<div id="menu">
    {menu}
</div>

<div id="content">
    {content}
</div>

</body>
</html>

4 个答案:

答案 0 :(得分:2)

您需要将变量发送到查看文件,如下所示

function index()
{
    $data['years'] = $this->getYears();             
    $data['menu'] = $this->getMenu();       
    $this->load->view('views/overview_screen.php',$data);
}

现在你可以使用$ year,$ menu作为视图文件中的变量

答案 1 :(得分:1)

根据输出,您的视图可能会通过CI的解析器库。

代码应该是这样的:

function index()
{
    $this->load->library('parser');
    $data['years'] = $this->getYears();             
    $data['menu'] = $this->getMenu(); 

    $this->parser->parse('overview_screen',$data);

}

我说这是因为我看到在视图文件中使用了括号,这就是CI使用自己的解析引擎的方式(因此{menu}被视为<?php echo $menu; ?>,后者又指的是索引&#39;菜单&#39;你在$ data数组中设置了

你经常称之为观点;它就像@praneeth代码,但没有使用php扩展! 这样:

$this->load->view('overview_screen',$data)

答案 2 :(得分:0)

如果var_dump函数/类之外的$menu变量,它将无效! 尝试使用:

function index()
{
    global $years;
    global $menu;
    $years = $this->getYears();             
    $menu = $this->getMenu(); 
}

答案 3 :(得分:0)

您能否提供更多代码示例,说明您在哪个地方进行转储调用,以及getMenu主体。这有助于了解$ years var

会发生什么
相关问题