Welcome Guest, Not a member yet? Register   Sign In
simple scope issue
#1

[eluser]dmol[/eluser]
Hi all,
I'm new to CI and indeed PHP classes and I'm having trouble with scope of variables.
I want to define a variable that can be used throughout a controller. It should be straightforward but the solutions I've seen don't seem to work for me.

I'm using CI version 2 and PHP version 5.1.6
<?php
Below are two basic versions of the controller:

This does not work:
Code:
class Main extends CI_Controller {

        var $data;  //I've also tried 'private $data' without success
      
        function Main()
                {
                parent::__construct();
                }
        function index()
                {   $this->data['name'] = "hello"; }
        function other()
                {
                 echo $this->data['name']; //fails. ['name'] is empty
                }
}
In the following version, the variable is visible in other functions but I think it's structure is causing problems when redirecting. I also don't know why an empty index function needs to be defined.
Code:
class Main extends CI_Controller {

        var $data;
      
        function Main()
                {
                parent::__construct();
                $this->data['name'] = "hello";
                }
        function other()
                {
                 echo $this->data['name']; //works. ['name'] contains hello
                }
        function index() //needs to be defined for some reason
                {
                }
}


Messages In This Thread
simple scope issue - by El Forum - 02-25-2011, 11:35 AM
simple scope issue - by El Forum - 02-25-2011, 11:56 AM
simple scope issue - by El Forum - 02-25-2011, 01:15 PM
simple scope issue - by El Forum - 02-26-2011, 02:32 AM
simple scope issue - by El Forum - 02-26-2011, 03:41 AM



Theme © iAndrew 2016 - Forum software by © MyBB