How to refer to a static constant member variable in PHP

后端 未结 2 1173
心在旅途
心在旅途 2021-02-20 09:49

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 contex

相关标签:
2条回答
  • 2021-02-20 10:32

    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();
    
    0 讨论(0)
  • 2021-02-20 10:36

    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';
        }
    }
    
    0 讨论(0)
提交回复
热议问题