I'm trying to store data from a shortcode attribute in a class property, so I can use it later in other functions. But somehow I'm always ending up with the initial value of the property. Here's a reduced example to showcase my problem:
class ScopeTestClass {
public $my_var = null;
function __construct() {
// The calls to add_action() go here
// I've omitted them for this example to avoid cluttering up the code
add_shortcode( 'my_shortcode', array($this, 'my_shortcode_handler'));
}
function register_scripts() {
wp_register_script('some_script', plugin_dir_url(__FILE__) .
'/js/some_script.js', array('jquery'), '1.0', true);
public function my_shortcode_handler() {
$this->my_var = 'yeeha!';
wp_enqueue_script('some_script');
wp_localize_script( 'some_script', 'somescript', array(
'ajax_url' => admin_url( 'admin-ajax.php' )));
}
public function ajax_handler() {
// This function handles the ajax call from some_script.js.
// When evaluating $this->my_var here, it is null.
}
}
$test_obj = new ScopeTestClass();
While my_var
is correctly set to "yeeha!" in the shortcode function, in the ajax_handler()
function it shows as null. Is this an issue of scope? I thought it might be because both the shortcode and the ajax handler functions are called from outside the object context and thus $this
doesn't point to test_obj
, but other questions and articles I've read didn't seem to have this problem. So.. what is my issue here?