How to refer to a static constant member variable in PHP

↘锁芯ラ 提交于 2020-01-01 08:47:52

问题


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
    }

}

回答1:


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';
    }
}



回答2:


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();


来源:https://stackoverflow.com/questions/1529039/how-to-refer-to-a-static-constant-member-variable-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!