0

I'd like to define a global object variable that I could use in several of the functions in my controller, Items.

Here's my code that doesn't work:

class Items extends CI_Controller {

 private $varname;

 function Items(){
  parent::__construct();
    $this->load->model('items_model');
    $folder_id=416;
    $this->varname=$this->items_model->getFilesById($folder_id);
 }

 function index(){
   var_dump($this->varname);    
 }

}

So $this->varname doesn't work as evidenced when I go to the url: localhost/items/index the printed ouput is this:

array(0) { }

1 Answer 1

1

Depending on your version of PHP, the constructor may not be called. Try changing

function Items(){

to

function __construct(){

and see if that fixes the problem.

http://php.net/manual/en/language.oop5.decon.php As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

That may be what is causing your problem.

Sign up to request clarification or add additional context in comments.

7 Comments

-@Greg thanks, I'm using PHP 5.3.1, unfortunately that didn't change the problem, its probably some Codeigniter weirdness, might there be any other way? Do I have to use the $this keyword to make it a global variable?
You have to use $this-> to refer to that instance's files variable. Where is files declared?
files isn't declared anywhere. I thought I could just assign files to the items_model data I retrieved. I don't need it to be called files. It can be anything just as long as I can call this variable throughout the class.
You can, I was just wondering if files was already defined by codeigniter, and that is what was causing the problem. Maybe choose another variable name and declare it using private $varname; at the top of the class, before the functions.
Try var_dumping $this->items_model->getFilesById($folder_id) in the constructor. Maybe the getfilesbyid is the problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.