I have a global variable outside my class = $MyNumber;
How do I declare this as a property in myClass?
For every method in my class, this is what I do:
class myClass() { private function foo() { $privateNumber = $GLOBALS['MyNumber']; } }
I want this
class myClass() { //What goes here? var $classNumber = ???//the global $MyNumber; private function foo() { $privateNumber = $this->classNumber; } }
EDIT: I want to create a variable based on the global $MyNumber but
modified before using it in the methods
something like: var $classNumber = global $MyNumber + 100;
Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.
A global variable is a visible variable and can be used in every part of a program. Global variables are also not defined within any function or method. On the other hand, local variables are defined within functions and can only be used within those function(s).
If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.
We declare a variable global by using the keyword global before a variable. All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration.
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.
Try to avoid globals, instead you can use something like this
class myClass() { private $myNumber; public function setNumber($number) { $this->myNumber = $number; } }
Now you can call
$class = new myClass(); $class->setNumber('1234');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With