I'm very new to PHP classes so forgive me if the answer is really obvious. I'm trying to figure out how to use a variable defined outside of a class inside of a class. Here is a very crude example
$myVar = 'value';
class myClass {
private $class_var = $myVar;
//REST OF CLASS BELOW
}
I know the above doesn't work, but how can I use the external $myVar inside the class?
functions outside any class are global an can be called from anywhere. The same with variables.. just remember to use the global for the variables... <? php function abc() { } $foo = 'bar'; class SomeClass { public function tada(){ global $foo; abc(); echo 'foo and '.
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.
As shown below, global variables can be accessed by any class or method within a class by simply calling the variable's name. Global variables can also be accessed by multiple classes and methods at the same time.
Variable defined inside the class: 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.
Try this:
$myVar = 'value';
class myClass {
private $class_var;
public function __construct($myVar) {
$this->class_var=$myVar;
}
//REST OF CLASS BELOW
}
When declaring the class, you will need to pass $myVar
like so, $myClass = new myClass($myVar);
.
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