Yeah, you can make this functionality.
From here "global variable" means kind of variables, mentioned in the question.
You can use static variable of the class to store the value of global variable.
class Bla {
static private $x;
}
To access this variable we can use couple of methods:
Make special setters and getters, I would recommend this as most simple and clear way:
class Bla {
static private $x = 'init value';
public function getX() {
return self::$x;
}
public function setX($value) {
self::$x = $value;
}
}
// Usage:
$obj1 = new Bla();
echo $obj1->getX();// init value
$obj1->setX('changed value');
Of course if appropriate you can use just static access syntax (public variables or static setters and getters), which is even more simple and clear, than first method. For example:
class Bla {
static public $x = 'init value';
}
// Usage:
echo Bla::$x;
Bla::$x = 3;
Also take in mind that objects are passing by references in PHP5.
class Bla {
private $date;
public function __construct(DateTime $x) {
$this->date = $x;
}
public function getDate() {
return $this->date;
}
}
$date = new DateTime();
// Usage:
$obj1 = new Bla($date);
$obj2 = new Bla($date);
/* now play with $objN->getDate()->.. and $date->..
* to see, that $x in both objects are referring to same variable. */
Now lets see at some not so good ways.
We can use magic setters and getters, which combined of a phpDoc can "emulate" behaviour of a real object variable (i mean in runtime it will get and set variable and in IDE, which supports phpDoc, you can even see variable in auto-completion). This solution violates the principle of encapsulation, so i wouldn't recommend common usage of it.
/**
* @property mixed $x My global var.
*/
class Bla {
static private $x = 'init value';
public function __set($name, $value) {
if ($name == 'x') {
self::$x = $value;
}
}
public function __get($name) {
if ($name == 'x') {
return self::$x;
}
}
}
// Usage:
$obj1 = new Bla();
echo $obj1->x;// init value
$obj1->x = 'changed value';
Same behaviour without magic we can get using references:
class Bla {
static $storage = 'init value';
public $x;
public function __construct() {
$this->x = &self::$storage;
}
}
Also we can make $x here private and add special access methods, what makes sense only if you HATE to use static syntax (self::).