0

I want to know if there is a way to store a global variable inside a class property so that it can be easily used by methods inside the class.

for example:

$variableGlobal = 30;

Class myClass{

    public $classProperty = global $variableGlobal;

    function myFunction(){
       $accessible = $this->classProperty;
}

now I know I can get the global variable by simply calling for it in the class function like so:

function myfunction(){
    global $variableGlobal;
}

I thought something like what I want in example 1 existed in but I could be flat out wrong, or I am right but I am approaching this the complete wrong way. Any ideas would be great thanks.

Forgot to mention alternatively I would be happy not to use a global and instead store the results of another class function inside the class variable

like so:

public $var = OtherClass::ClassFunction();
4

3 回答 3

0

You can use the construct method and pass by reference. Inject the value to the constructor when you instantiate the class, and by using reference operator &, you can access the global variable at any time and pick up the current value.

You can also just access the global via $GLOBAL structure within the class. See the example here:

<?php

$variableGlobal = 30;

class myClass{

    public $classProperty;

    public function __construct(&$globalVar){
        $this->classProperty = &$globalVar;
    }

    public function myFunction(){
       $accessible = $this->classProperty;
        // do something interesting
        print "$accessible\n";
    }

    public function accessGlobal(){
        print $GLOBALS["variableGlobal"] . "\n";
    }

}


$thisClass = new myClass($variableGlobal);
$thisClass->myFunction();
$GLOBALS["variableGlobal"] = 44;
$thisClass->myFunction();
$variableGlobal = 23;
$thisClass->accessGlobal();

Recommended reading

于 2013-09-18T20:25:19.423 回答
0

The value you want should be available anywhere in the GLOBALS variable using the variable name as the key.

public $classProperty = GLOBALS[$variableGlobal]

However, I would suggest, to avoid unnecessary coupling and allow for testing, you may want to pass the value in the global in to the class.

于 2013-09-18T20:26:14.563 回答
0

Figured it out, used a solution to solve my problem from another question:

PHP class: Global variable as property in class

于 2013-09-18T20:37:12.730 回答