Welcome Guest, Not a member yet? Register   Sign In
Scope of $data problems
#8

[eluser]CroNiX[/eluser]
Class variables, aka properties, are accessible only when using $this, as $this refers to the entire object, not the individual method. So you need to use $this to access individual class properties throughout the class.

Code:
class Someclass extends CI_Controller {

  public $data;  //class property declaration, only accessible by using $this->data

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

    $this->data = 'my property data';  // populate property on construct
    echo $this->data; // 'my property data'
  }
  
  function some_function()
  {
    $data = 'test'; //this is a local variable only available to this method, some_function().

    $this->data = 'other data'; //this is setting the class property, $data

    echo $data; // "test"
    echo $this->data // "other data"
  }

  function another_function()
  {
    echo $this->data;  // 'my property data'

    echo $data;  //this is undefined in this method as it is defined in some_function
  }
}

In the above, when the class is instantiated, it sets the property, $data and echos it.
'my property data'

If you go to /someclass/some_function:
-goes through constructor first, sets property $data and echos it
-sets local variable $data, sets property $data and echoes them both
'my property data'
'test'
'other data'

If you go to /someclass/another_function
-goes through constructor first, sets property $data and echos it
-echos property $data, again
-produces error that variable $data is undefined as it's only available within some_function where it was declared as a local variable.
'my property data'
'my property data'
error, $data is undefined

Hope that helps a bit. There is a difference between class variables and local variables, and you have to access them as such.


Messages In This Thread
Scope of $data problems - by El Forum - 06-22-2012, 07:06 AM
Scope of $data problems - by El Forum - 06-22-2012, 07:13 AM
Scope of $data problems - by El Forum - 06-22-2012, 07:37 AM
Scope of $data problems - by El Forum - 06-22-2012, 07:46 AM
Scope of $data problems - by El Forum - 06-22-2012, 07:51 AM
Scope of $data problems - by El Forum - 06-22-2012, 09:14 AM
Scope of $data problems - by El Forum - 06-22-2012, 10:14 AM
Scope of $data problems - by El Forum - 06-22-2012, 10:30 AM



Theme © iAndrew 2016 - Forum software by © MyBB