OO PHP从另一个类访问公共变量

问题描述:

我有一个类似于以下的课程:

I have a class like the following:

class game {

    public $db;
    public $check;
    public $lang;

    public function __construct() {

        $this->check = new check();

        $this->lang = DEFAULT_LANG;
        if (isset($_GET['lang']) && !$this->check->isEmpty($_GET['lang']))
            $this->lang = $_GET['lang'];
    }

}

如您所见,我有一个公共变量$lang,它也是通过构造函数定义的.

As you can see I have a public variable $lang that is also defined via the contructor.

问题是我想从与该类没有直接关系的其他类中访问此变量的结果,因为我不想为每个不同的类重新声明它.

The proble is that I want to access the result of this variable from other classes that are not directly related to this class, since I don't want to redeclare it for each different class.

例如,我如何从另一个类中调用该变量的结果,让它称为class Check?

So for example how can I call the result of that variable from another class, lets call it class Check ?

如果将public $lang;标记为静态:

public static $lang;

您可以通过game::$lang;

如果不是静态的,则需要制作一个游戏实例并直接访问它:

if not static, you need to make an instance of game and directly access it:

$game = new game;
$game->lang;

(当前)类内的静态调用:

static call inside of (current) class:

self::$lang;

后期静态绑定调用(针对继承的静态变量):>

late static bound call (to inherited static variable):

static::$lang;

从子类到父级的呼叫:

parent::$lang;

实例内部的常规调用(实例是使用new Obj();的时间):

normal call inside of an instance (instance is when you use new Obj();):

$this->lang;

顺便说一句: define('DEFAULT_LANG', 'en_EN');定义的变量是GLOBAL范围,意味着可以在任何地方访问!

BTW: variables defined by define('DEFAULT_LANG', 'en_EN'); are GLOBAL scope, mean, can access everywhere!

<?php
define('TEST', 'xxx');

class game {
    public function __construct() {
        echo TEST;
    }
}

//prints 'xxx'
new game;