Welcome Guest, Not a member yet? Register   Sign In
Access Class Variable inside another class
#1

[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?
#2

[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.
#3

[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
#4

[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;
  }
}
#5

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

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

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




Theme © iAndrew 2016 - Forum software by © MyBB