Shubham Maurya Shubham Maurya -4 years ago 104
PHP Question

Not able to access public variable outside class in wordpress

For the given class I can not access the public variable outside class.I want to access variable payload and

$_GLOBALS['te']
outside the class but it is giving
NULL
value.

It should show value of payload outside of class when I print payload variable inside
show_data()
it is returning the correct value.

<?php

class google_api
{
public $test;
public $payload;
public $id_token;


function add_platform_script()
{
wp_enqueue_script('platform_scr', 'https://plus.google.com/js/client:platform.js', false);
wp_enqueue_script('handler_callback', plugins_url('../js/google_sign.js', __FILE__), false);
add_action('wp_enqueue_scripts', array ($this, 'add_platform_script'), 1);
wp_localize_script('handler_callback', 'show_vfr', array ('ajaxurl' => admin_url('admin-ajax.php')));
}

public function add_api_js()
{
$this->add_platform_script();
echo
'<meta name="google-signin-client_id" content="MY CLIENT ID"><div class="g-signin2"
data-scope="profile email"
data-onsuccess="onSignIn"
data-onfailure="onSignInFailure"> </div>';
$GLOBALS['te'] = 'helloee';
}

function show_data($client)
{
if (isset($_POST['Token'])) {
$this->id_token = $_POST['Token'];
$CLIENT_ID = 'MY CLIENT ID';
$client = new Google_Client(['client_id' => $CLIENT_ID]);

$this->payload = $client->verifyIdToken($this->id_token);
if ($this->payload) {
$user_email = $this->payload['email'];
if (email_exists($user_email)) {
$user = get_user_by('email', $user_email);
if ($user) {
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID);
do_action('wp_login', $user->user_login);
die('1');
}
} else {
die('2');
}
} else {
echo 'INVALID TOKEN ISSUED [ERR 005]'; // Invalid ID token
}
} else {
echo 'INVALID USER';
}
}

}

$foo = new google_api();
add_action('google_button_form', array ($foo, 'add_api_js'));
var_dump($foo->payload);
var_dump($GLOBALS['te']);
add_action('wp_ajax_nopriv_show_data', array ($foo, 'show_data'));

Answer Source

I think you are confused about how filters work, and when your code is actually executed.

Your property payload wont be set until the method show_data runs, and that wont happen until the action wp_ajax_nopriv_show_data is triggered. (By accessing the proper ajax URL).

Since the object will exist only during that request, your payload property will be only accessible inside that same method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download