Global Variables inside a class

Hello,

How do I make global variables inside a class so that all my functions can see it. In Java, this process was really simple, all you had to do was declare a variable outside of the function and all the functions could see it’s scope.

In PHP, i am having trouble understanding on how to achieve this. To clarify, I have a database that I pull a word from, I want to be able save that word into a variable and access it via another function. I am new to programming so a simple explanation would be great.

THanks.

You could set the variable to the global scope like this:

[php]class test {

public function __construct() {
global $blah;
$blah = ‘foo’;
}
}

class testUsage {

public function __construct() {
global $blah;
var_dump($blah);
}
}

$test = new test();
$testUsage = new testUsage();[/php]

Using globals are considered bad practice though. You should really look into inheritance and dependency injection. This would be more preferred solutions:

Inheritance:
[php]class test {

public $blah;

public function __construct() {
$this->blah = ‘foo’;
}
}

class testUsage extends test {

public function __construct() {
parent::__construct();
var_dump($this->blah);
}
}

$testUsage = new testUsage();[/php]

Dependency injection:
[php]class test {

public $blah;

public function __construct() {
$this->blah = ‘foo’;
}
}

class testUsage {

public function __construct($test) {
var_dump($test->blah);
}
}

$test = new test();
$testUsage = new testUsage($test);[/php]

If you do this a lot then perhaps a dependency container is what you’re after

If you’re on PHP > 5.4 you can use traits
http://php.net/manual/en/language.oop5.traits.php

Sponsor our Newsletter | Privacy Policy | Terms of Service