Php &引用;未定义变量";在构造函数中设置$data[';变量';]时在视图中;在功能中设置时工作

Php &引用;未定义变量";在构造函数中设置$data[';变量';]时在视图中;在功能中设置时工作,php,codeigniter,Php,Codeigniter,如果我在函数index()中设置$data['error'],并在视图中设置echo$error,它将显示在我的视图页面中。但是,如果我像下面那样在构造函数中设置变量,并尝试在视图页面中echo$error,则会显示严重性: 注意消息:未定义变量:错误 是,因为您只在构造函数功能块的本地定义$data 如果希望任何类功能块都可以访问变量 然后可以创建类的新属性 public $data; private $data; 然后 在构造函数块上,您可以像 $this->data['error'

如果我在函数
index()
中设置
$data['error']
,并在视图中设置
echo$error
,它将显示在我的视图页面中。但是,如果我像下面那样在构造函数中设置变量,并尝试在视图页面中
echo$error
,则会显示严重性:

注意消息:未定义变量:错误


是,因为您只在构造函数功能块的本地定义$data

如果希望任何类功能块都可以访问变量

然后可以创建类的新属性

public $data;
private $data;
然后

在构造函数块上,您可以像

$this->data['error'] = 'hellow';
和在函数索引块上

$this->data['main_content'] = 'login';

这是由于范围的原因,以下是一个简短的示例:

<?php

class Login extends CI_Controller
{
    /**
     * @var  array  only accessable within the scope of $this, inside Login class
     */
    private $data = [];

    public function __construct()
    {
        $foo = 'bar';
        $this->data = ['error' => 'hello'];
    }

    public function index()
    {
        var_dump($foo); // Severity: Notice Message: Undefined variable: foo
        // it's only available in the scope of __construct()

        $this->data['main_content'] = 'login';

        // here you pass $this->data and then CI will extract the array keys
        // giving you access to the $error variable
        $this->load->view('inc/template', $this->data);
    }
}

$data
在控制器的每个功能中都被视为不同的

如果在构造函数中创建一个
$data
,在索引中创建一个相同的变量,则它们被视为不同的变量,其作用域也是局部的

公共函数u_construct()应包含:

公共函数索引()应包含:

请记住仅此功能中的资源


或者在类中创建$data作为全局变量,并在需要时将其用作
$this->data

似乎您不了解变量在此问题上的作用域

试试这样的

class Login extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->data['error'] = 'hello';
    }
    function index()
    {
        //$data['error'] = 'hello';

        $data['main_content'] = 'login';
        $this->load->view('inc/template', $this->data);
    }
}

You can then also pass it to the view using the variable $this->data too.

因为$error不存在,$data['error']不存在。。。但是这个变量是这个构造函数的局部变量,你怎么会试图访问它呢?我明白了。如果我想将$data['error']的初始值设置为'hello',我将重定向到另一个函数中的login/index并能够覆盖初始值,我该如何做?
$data['main_content']='login'
应该是
$this->data['main_content']='login'和类中具有适当作用域的变量声明,
public$data
 allocating resources used in entire class ex. $this->load
 check user authentication (if entire class requires it)
 allocating resources used only in this function
 calling views or displaying anything
class Login extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->data['error'] = 'hello';
    }
    function index()
    {
        //$data['error'] = 'hello';

        $data['main_content'] = 'login';
        $this->load->view('inc/template', $this->data);
    }
}

You can then also pass it to the view using the variable $this->data too.