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'];
}
}
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.
So for example how can I call the result of that variable from another class, lets call it class Check
?
if you mark the
public $lang;
as static:you can access it via
game::$lang;
if not static, you need to make an instance of game and directly access it:
static call inside of (current) class:
late static bound call (to inherited static variable):
call from child class to parent:
normal call inside of an instance (instance is when you use
new Obj();
):BTW: variables defined by
define('DEFAULT_LANG', 'en_EN');
are GLOBAL scope, mean, can access everywhere!A variable doesn't have a result. If you mean to retrieve the state of that variable on a specific object
$obj
of classgame
then you can simply do:On a side note if
$lang
is publicly only read only you should protect it by defining itprivate
orprotected
and create a getter method instead.If you mean that you want to use the same variable name in another class I'd suggest you to consider inheritance:
but the variable of the two objects will be different.
Since the property is public, you can access it from outside the class as
$objInstance->property
. It doesn't matter if you're calling it from a function, procedural script, in another object. As long as you have the instance, you can call it's public property. Ex:Also, some advice on working with objects and such: It's considered better code if you don't create instances of objects in the other objects, but rather pass them in someway (either a setter method or through the constructor). This keeps the classes loosely coupled and results in code that is more reusable and easier to test. So:
The first half of this article is an accessible explanation of what is known as Dependency Injection.
you can make it static variable, so you will be able to call it anytime anywhere, the diff is that instead of
when editing it(Works inside class game only) you do :
and when you call/edit it (Works everywhere) from anther class you do :
the idea of static class is that its exist only in one instance, so only one $lang exist in your program. but there is no need to load the whole class to get acsess to it.