如何在PHP中引用一个静态常量成员变量

如何在PHP中引用一个静态常量成员变量

本文介绍了如何在PHP中引用一个静态常量成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类包含成员变量。 当从静态上下文调用类时,PHP中的语法如何访问类中的成员变量?

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.

或者如果有更好的方法,那么我建议,请与我分享(我是新的PHP)
谢谢!

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!

例如


class example
{
    var $apple;

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

}


推荐答案

为了简洁,我只提供php 5版本:

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

这篇关于如何在PHP中引用一个静态常量成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 21:24