views:

731

answers:

2

I have a class with member variables. What is the syntax in PHP to access the member variables from within the class when the class is being called from a static context?

Basically I want to call a class method (but not create a new object), but when the class method is called, I want a handful of static constant variables to be initialized that need to be shared among the different class methods.

OR if there's a better way to do it then what I'm proposing, please share with me (I'm new to PHP) Thanks!

eg.

class example
{
    var $apple;

    function example()//constructor
    {
        example::apple = "red" //this throws a parse error
    }

}
+4  A: 

For brevity sake I will only offer the php 5 version:

class Example
{
    // Class Constant
    const APPLE = 'red';

    // Private static member
    private static $apple;

    public function __construct()
    {
        print self::APPLE . "\n";
        self::$apple = 'red';
    }
}
Chris Kloberdanz
"Example::$apple = 'red';" Works if you are outside the scope of the Example class.
camomileCase
If $apple is public.
camomileCase
Thanks Chris. the self:: in addition to declaring the variable as a private static was what I was looking for :)
justinl
+1  A: 

Basically I want to call a class method (but not create a new object), but when the class method is called, I want a handful of static constant variables to be initialized that need to be shared among the different class methods.

Try this

class ClassName {
  static $var;

  function functionName() {
    echo self::$var = 1;
  }
}

ClassName::functionName();
lemon
thanks lemon! this is also what I was looking for.
justinl