Reputation: 4284
I am trying to access an array set in a model from a codeigniter controller, and things are acting odd.
Currently all I have in the model is this:
class Pages_model extends CI_Model {
function __construct()
{
parent::__construct();
}
var $pages = array(
'draw', 'stackoverflow', 'words'
);
}
I can see the array is being set because when I execute
$this->load->model('Pages_model');
die(var_dump(get_object_vars($this->Pages_model)));
I get the output
array
'pages' =>
array
0 => string 'draw' (length=4)
1 => string 'stackoverflow' (length=13)
2 => string 'words' (length=5)
But when I try to access the variable itself:
$this->load->model('Pages_model');
die(var_dump($this->Pages_model->$pages));
I get an error:
Message: Undefined variable: pages
This does not make any sense to me. What is going on????
Upvotes: 0
Views: 3777
Reputation: 1279
Make static member:
class Model_name {
static $member='nothing';
}
//and use it with scope resolution operator '::'
$m = new Model_name();
echo $m::member; //output: nothing
$m::member = 'something';
echo $m::member; //output: something
Upvotes: 0
Reputation: 474
You can access the variable directly, if you define it like this :
class Pages_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->pages = array(
'draw', 'stackoverflow', 'words'
);
}
}
Then you would call it by: $this->pages_model->pages
Upvotes: 0
Reputation: 8528
I'm not sure you can directly access variables in a model I believe you can only call functions, perhaps make a getter function for the variable and return the variable. eg.
Model Page
function get_pages() {
return this->pages;
}
Controller
$pages = $this->Pages_model->get_pages();
Upvotes: 1
Reputation: 5024
Try $this->Pages_model->pages, without the $ before pages.
When you do this:
$this->Pages_model->$pages
PHP tries to evaluate the variable of $pages, which is null (Pages_model->null).
Upvotes: 6