I want to access to variable "$sha256" from one function in other one that use both of them an add_action for Ajax call. I read that I must use a class function and add add_action with construct. I followed advice from [codex][1], but it seems I always an error ! Currently my Jquery Ajax call doesn't send response from functions.php.
Could you please tell me why ? Here is an example from my code:
class sendObjectClass{
$sha256 = "";
public function __construct() {
add_action( 'wp_ajax_vault', array( $this ,'vault' ));
add_action( 'wp_ajax_nopriv_ vault', array( $this ,'vault' ));
add_action( 'wp_ajax_ retrievedK', array( $this ,'retrievedK' ));
add_action( 'wp_ajax_nopriv_ retrievedK', array( $this ,'retrievedK'));
}
public function vault(){
$sha256 = .....;
echo json_encode(some elements);
}
public function retrievedK(){
echo json_encode($sha256);
}
}
Must I add : new sendObjectClass(); ?
Thanks for your help.
[1]: https://developer.wordpress.org/reference/functions/add_action/#div-comment-355
Edit: With the advice I received I tried this but it doesn't work. I work inside function.php.
class ajaxgenk_handler
{
private string $hash;
private $C1 = array();
public function __construct(string $hash, $C1)
{
$this->hash = $hash;
$this->C1 = $C1;
}
public function run()
{
add_action( 'wp_ajax_vault', array( $this, 'vault' ));
add_action( 'wp_ajax_nopriv_vault', array( $this, 'vault' ));
add_action( 'wp_ajax_retrievedK', array( $this, 'retrievedK' ) );
add_action( 'wp_ajax_nopriv_retrievedK', array( $this , 'retrievedK' ) );
}
public function vault()
{
//php code to generate vars for decrypt1 array
$decrypt1 = array($kchrfst, $kintfst, $kchrlst, $kintlst);
$logiq = 1;
$datasecure['keygen'] = $this->C1;
$datasecure['decryptor'] = $decrypt1;
$datasecure['enigma'] = $logiq;
echo json_encode($datasecure);
wp_die();
}
public function retrievedK()
{
echo json_encode(['retrik' => $this->hash]);
wp_die();
}
}
require_once( get_template_directory() .'/cryptograph.php');
use class\Cryptograph;
add_action( 'plugins_loaded', 'genk_handler' );
function genk_handler() {
//php code to generate vars for $C1 array
$C1 = array($fstcchr, $fstint, $lstchr, $lstint,$fstchrpos,$lstchrpos);
$hash = 'thekeygenerated';
$handler = new ajaxgenk_handler($hash,$C1);
$handler->run();
}