CodeIgniter中出现Undefined variable: menu错误,请求排查解决
Hey there! I see exactly what's causing that error—you're using an extra dollar sign when accessing your class property. Let's break this down and fix it.
The Root Cause
Your code uses $this->$menu when trying to access the private class property $menu. This syntax is for variable variables in PHP, which means PHP is looking for a local variable named $menu (which you haven't defined) to use as the property name. What you actually want is to directly reference the class property with $this->menu.
Corrected Code
Here's the fixed version of your Dashboard controller:
<?php class Dashboard extends CI_Controller { private $menu; public function __construct() { parent::__construct(); $this->load->model('menu_model'); // Removed the extra $ from $this->$menu $this->menu = $this->menu_model->generateTree($items = array()); } public function index() { // Also removed the extra $ here $data['menu'] = $this->menu; $this->load->view('dashboard/dashboard', $data); } }
Key Fixes
- In the constructor: Changed
$this->$menuto$this->menuwhen assigning the menu data from your model - In the
index()method: Changed$data['menu'] = $this->$menu;to$data['menu'] = $this->menu;to correctly pass the class property to your view
This should eliminate the "Undefined variable: menu" error while keeping your menu functionality working as expected.
内容的提问来源于stack exchange,提问作者Thisaru

