Reputation: 312
I need to print first segment variable in my function from __construct, but I get error:
Code:
<?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 */
Error:
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
I'm trying to search it in Google and Stackoverflow But I cant fix this problem. Thanks all.
Upvotes: 0
Views: 2232
Reputation: 527
As Manual http://php.net/manual/en/language.oop5.visibility.php
You can access public variable by
$this->data['seg']=..........;
Upvotes: 2
Reputation: 4547
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";
}
}
Upvotes: 0
Reputation: 1098
You have to use $this
to set or get value of $data
which is in class
scope. I have fixed your code here, give a try.
<?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";
}
}
Upvotes: 3