CodeIgniter Forums
Access Class Variable inside another class - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Access Class Variable inside another class (/showthread.php?tid=6209)



Access Class Variable inside another class - El Forum - 02-18-2008

[eluser]adamp1[/eluser]
I have the following setup
Code:
class Page extends Controller
{
  function Page()
  {
    $this->_variable = "something";
  }

  function index()
  {
    $this->Library->method();
  {
}

class Library
{
  function method()
  {
    // Use $_variable
  }
}

So is there a way the library can access the variable without it being passed explicitly to the class/method?


Access Class Variable inside another class - El Forum - 02-18-2008

[eluser]Negligence[/eluser]
Create a get() method to retrieve the variable, and pass $this (the controller object) to the Library when you create it. Then just call $controllerObj->getVar() from within the library.


Access Class Variable inside another class - El Forum - 02-18-2008

[eluser]Sean Murphy[/eluser]
Option 1) Library extends Page
Option 2) Instantiate Page inside of Library and access the member variable like $page->_variable or using a get() method


Access Class Variable inside another class - El Forum - 02-18-2008

[eluser]m4rw3r[/eluser]
You can also make the property static:
Code:
class Page extends Controller
{
  static $_variable;
  function Page()
  {
    $this->_variable = "something";
  }

  function index()
  {
    $this->Library->method();
  {
}

class Library
{
  function method()
  {
    // Use $_variable
    echo Page::$_variable;
  }
}



Access Class Variable inside another class - El Forum - 02-18-2008

[eluser]Seppo[/eluser]
If Page is the current controller you can

Code:
$CI =& get_instance()
$CI->_variable



Access Class Variable inside another class - El Forum - 02-19-2008

[eluser]adamp1[/eluser]
Thanks for the help guys will have to give them a go now.