In a PHP class, is there a way to set set a global variable that doesn't need to be called in each function?
For example, I have a variable called $settings
which contains an array of values:
Array( [option_1] => on, [option_2] => on, [option_3] => off )
The get_option()
function comes from WordPress. The values in the $settings
array determine which functions to run:
class My_Class {
public function __construct() {
# Get array of options
$settings = get_option( 'my_options' );
if ( is_array( $settings ) || is_object( $settings ) ) {
if ( $settings['option_1'] == 'on' ) {
add_action( 'tag_1', array( $this, 'function_1' ) );
}
if ( $settings['option_2'] == 'on' ) {
add_action( 'tag_2', array( $this, 'function_2' ) );
}
}
}
public function function_1() {
# Call the array of options again
$settings = get_option( 'my_options' );
echo 'This option is ' . $settings['option_1'];
}
public function function_2() {
# Code here...
}
new My_Class();
However, I call the following line twice in my __construct()
and function_1()
:
$settings = get_option( 'my_options' );
Instead of calling this variable twice in two different functions, what's the proper way of calling the same variable which can be used within different functions of my class? I tried adding the $settings
variable function just below the class My_Class
, but that didn't work:
class My_Class {
global $settings = get_option( 'my_options' );
# Rest of the code below...