Codeigniter:__construct变量到我的另一个函数中

时间:2017-02-03 07:16:36

标签: php codeigniter

我需要在__construct中打印我的函数中的第一个段变量,但是我收到错误:

代码:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

    public $data = array();

    public function __construct()
    {
        parent::__construct();
        $data['seg'] = $this->uri->segment(1);
        $data['seg'] == 'en' ? $data['seg'] = 'en' : $data['seg'] = 'ge';
    }

    public function index()
    {
        echo "test";
    }

    public function Test()
    {
        echo $data['seg'] . " - TEST";
    }

}

/* End of file  */
/* Location: ./application/controllers/Main.php */

错误:

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data

Filename: controllers/Main.php
Line Number: 21
Backtrace:
File: D:\www\test\application\controllers\Main.php
Line: 21
Function: _error_handler
File: D:\www\test\index.php
Line: 315
Function: require_once

- TEST

我正在尝试在Google和Stackoverflow中搜索它但我无法解决此问题。谢谢大家。

3 个答案:

答案 0 :(得分:2)

作为手动http://php.net/manual/en/language.oop5.visibility.php

您可以通过

访问公共变量
$this->data['seg']=..........;

答案 1 :(得分:2)

您必须使用$this设置或获取$data范围内的class的值。我在这里修改了你的代码,试一试。

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller
{
    public $data = array();

    public function __construct()
    {
        parent::__construct();

        $this->data['seg'] = $this->uri->segment(1);
        $this->data['seg'] == 'en' ? $this->data['seg'] = 'en' : $this->data['seg'] = 'ge';
    }

    public function index()
    {
        echo "test";
    }

    public function Test()
    {
        echo $this->data['seg'] . " - TEST";
    }
}

答案 2 :(得分:0)

class Main extends CI_Controller {

    public $data = array();    

    public function __construct()
    {
        parent::__construct();
        $this->data['seg'] = $this->uri->segment(1);
        $this->data['seg'] == 'en' ? $this->data['seg'] = 'en' : $this->data['seg'] = 'ge';
    }

    public function index()
    {
        echo "test";
    }

    public function Test()
    {
        echo $this->data['seg'] . " - TEST";
    }

}