Welcome Guest, Not a member yet? Register   Sign In
Accessing a classes static var in a controller
#1

[eluser]stevefink[/eluser]
Hi folks,

Had a quick inquiry on accessing a var in one of my libraries. I can't seem to get the scope down the proper way.

The scenario is I have a class loaded as a library that looks like the following:

class Foo {

static $bar = 'hello world';
//-- more code --//
}

Now in my controller I have the customary $this->load->library('foo'); in my constructor. Now I can easily write a getter funct to access $bar with something like:

function getBar() { return $self::bar; }

I'd like to be able to access the variable using the scope resolution operator (:Smile, sort of like:

echo Foo::$bar; How do I reach that context within a controller?

Cheers, thanks!

/sf
#2

[eluser]thurting[/eluser]
http://us2.php.net/manual/en/language.oop5.static.php
#3

[eluser]stevefink[/eluser]
It's rather odd. I have something similar to:

Code:
class Foo {

    const bar = 'hi';
    
    function Foo() {}
    function getBar() { return self::bar; }

}

In my controller when I call, $this->foo->getBar(), I see something such as this:

[17-Apr-2008 21:17:47] PHP Fatal error: Call to a member function getBar() on a non-object in /www

Is it not loading the library properly?
#4

[eluser]wiredesignz[/eluser]
Yes you can access a static var in PHP4
Code:
class Foo
{
    var $bar;

    function Foo()
    {
        static $bar = 'Hello World';
        
        $this->bar =& $bar;    //assign the class var as reference to the static var
    }
}
#5

[eluser]Michael Ekoka[/eluser]
@stevefink:
- about accessing static variables with the scope resolution operator: I think you answered your question in the first post. If the variable is static, it means that it belongs to the non instantiated class, not its objects. So you can access it with the class name Foo::$bar, even inside your controller.
- about the error message: yes it means that the library's object wasn't instantiated.




Theme © iAndrew 2016 - Forum software by © MyBB