PHP class: Global variable as property in class
You probably don't really want to be doing this, as it's going to be a nightmare to debug, but it seems to be possible. The key is the part where you assign by reference in the constructor.
$GLOBALS = array(
'MyNumber' => 1
);
class Foo {
protected $glob;
public function __construct() {
global $GLOBALS;
$this->glob =& $GLOBALS;
}
public function getGlob() {
return $this->glob['MyNumber'];
}
}
$f = new Foo;
echo $f->getGlob() . "\n";
$GLOBALS['MyNumber'] = 2;
echo $f->getGlob() . "\n";
The output will be 1
2
which indicates that it's being assigned by reference, not value.As I said, it will be a nightmare to debug, so you really shouldn't do this. Have a read through the wikipedia article on encapsulation; basically, your object should ideally manage its own data and the methods in which that data is modified; even public properties are generally, IMHO, a bad idea.
PHP use global variables in class/object
The right way would be to use a constructor - a method that will run when the object is created.
When you define class properties, you can only use constant values (1
, 'xyz'
, array()
are fine for example), not expressions that need to be evaluated at runtime.
Pass the variable to the constructor, and don't use global variables.
class myObject {
public $username;
public $zzz;
public function __construct($variable) {
$this->username = $variable + 5 ;
$this->zzz = $this->username + 5;
}
}
$obj = new myObject(10);
echo $obj->username; //15
In PHP, you don't need to use classes and objects if you don't want to write OOP code. You can simply create good old functions. But if you want to use them, try to get familiar with OOP concepts. How do declare global variable in PHP class
First up, you're not trying to create a "global variable" (as your title suggests), but a private member variable.
In order to do that you need to declare the private member variable outside of the constructor:
class Auth extends Controller {
private $pass;
function __construct(){
}
function auth()
{
parent::Controller();
$this->load->library('session');
$this->load->helper('cookie');
$this->load->library('email');
}
function index(){
..........
}
function loging(){
$this->pass = "Hello World";
}
function test(){
echo $this->pass;
}
}
Also:- Correct the name of your constructor
- Chose a naming convention (e.g. lowercase first character of function names) and stick to it.
<?php
class Auth {
private $pass;
function __construct(){
}
function loging(){
$this->pass = "Hello World";
}
function test(){
echo $this->pass;
}
}
$oAuth = new Auth();
$oAuth->loging();
$oAuth->test();
?>
It outputs:C:\>php test.php
Hello World
How to use the global variable to initialize the class property?
To access a global variable you need to use the global variable with global
keyword, Secondly your modifier and class shares the same name which afaik will confuse the compiler see the below snippet
Nope It doesn't
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
class foo
{
public $foo;
function __construct()
{
global $str;
$this->foo = $str;
}
}
$foo = new foo();
echo $foo->foo;
?>
SnippetWhy not to use global variables
Class Property Containing a Global Variable
Figured it out, used a solution to solve my problem from another question:
PHP class: Global variable as property in class
PHP: set a global variable in a class
You can declare $settings as a class property
protected $settings;
Then inside __construct
$this->settings = get_option( 'my_options' );
You can then access it anywhere inside the class using $this->settings
public function function_1() {
echo 'This option is ' . $this->settings['option_1'];
}
For more details about properties
, you can refer to PHP documentation http://php.net/manual/en/language.oop5.properties.php How to pass Global variables to classes in PHP?
Well, you can declare a member variable, and pass it to the constructor:
class Administrator {
protected $admin = '';
public function __construct($admin) {
$this->admin = $admin;
}
public function logout() {
$this->admin; //That's how you access it
}
}
Then instantiate by:$adminObject = new Administrator($admin);
But I'd suggest trying to avoid the global variables as much as possible. They will make your code much harder to read and debug. By doing something like above (passing it to the constructor of a class), you improve it greatly... Access global variables and static class properties of another file, without bringing those into scope
My solution here was to create a version of my “sub-subject” code that, instead of echo
’ing HTML, echo
’ed a JSON of the variables I was interested in with json_encode
.
Then the other file used json_decode(`php sub-subject-json.php`);
. The backtick operator executes a shell command, in this case, php
itself called with the file I want to look at.
So, for example, where previously I might have had
minion.php
<?php
$name = 'Steve';
$attack = 3;
$damage = '1d6+3';
?><!DOCTYPE html>
<html>
<head><title><?php echo $name; ?></title></head>
<body>
<h1><?php echo $name; ?></h1>
<p><?php echo formatBonus($attack) . " $damage"; ?>
</body>
</html>
Now I haveminion-core.php
<?php
$name = 'Steve';
$attack = 3;
$damage = '1d6+3';
?>
minion.php
<?php require_once('minion-core.php'); ?><!DOCTYPE html>
<html>
<head><title><?php echo $name; ?></title></head>
<body>
<h1><?php echo $name; ?></h1>
<p><?php echo formatBonus($attack) . " $damage"; ?>
</body>
</html>
minion-json.php
<?php
require_once('minion-core.php');
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'name' => $name,
'attack' => $attack,
'damage' => $damage,
]);
?>
And then my main file can includeleader.php
$steve = json_decode(`php minion-json.php`);
This is a nasty, ugly hack. But it does work, and it works without refactoring everything I’ve written. PHP global variable inside a class
Use static variables if you want them to have one and the same value, available regardless of their class instances (tutorial):
class bla
{
private static $x;
public function setx($x) {
self::$x = $x;
}
public function getx() {
return self::$x;
}
}
$object1 = new bla();
$object1->setx(5);
echo $object1->getx();
echo '<br>';
$object2 = new bla();
echo $object2->getx();
Output:5
5
Related Topics
Howto Generate JSON with Smarty
Different Timezone_Types on Datetime Object
File_Get_Contents(): Stream Does Not Support Seeking/When Was PHP Behavior About This Changed
Share Variables/Memory Between All PHP Processes
Creating and Invoking an Anonymous Function in a Single Statement
Docx File Type in PHP Finfo_File Is Application/Zip
Pdo Prepared Statements for Insert and on Duplicate Key Update with Named Placeholders
Remove Namespace from Xml Using PHP
Can't Change Font Size for Gd Imagestring()
Remove Extra Spaces But Not Space Between Two Words
Compare Object Properties and Show Diff in PHP
How to Watch a File Write in PHP
How to Remove Text Between Tags in PHP
Prevent Back Button After Logout
PHP - Ini_Set('Session.Gc_Maxlifetime', 5) - Why It Doesn't End the Session
MySQL Fulltext Search Multiple Words
Php: How to Read a File Live That Is Constantly Being Written To