Support » Developing with WordPress » how to share the variable to different function on the same class

  • I want to print what I input in wordpress, but I still not get the variable from different function in the same class
    The following is my code:

    class Test{
        private $infos;
          
        function get_info() {
            if ( isset($_REQUEST['my_info']) ) {
                $this->infos = $_REQUEST['my_info'];
                echo 'your input is:'.$this->infos;
            }
            
            // Always die in functions echoing ajax content or it will display 0 or another word
        //    die();
        }
        
        function salcodes_year() {
            echo 'the data is:'.$this->var;
            return $this->var;        
        }
    
        function js2php_register(){
            add_action( 'wp_ajax_test_info', array($this, 'get_info') );
            add_action( 'wp_ajax_nopriv_test_info', array($this, 'get_info') );
            add_shortcode( 'current_year', array($this, 'salcodes_year') );
        }
        
    }
    
    $test = new Test;
    $test->js2php_register();

    Version:
    WordPress 5.8.2
    PHP 7.4.27
    MySQL 5.7.37 Community Server (GPL)

    Help me, please!

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    $var is never assigned anywhere. You assign $infos with an Ajax request, that’s fine, but you’re not using $infos anywhere else. Once assigned, class properties are available in other class methods. For example, add this to your class:

    private $var2;
    function __construct() {
       $this->var2 = 'foo';
    }
    function get_var2() {
        return $this->var2;
    }

    then after instantiating your class object, you could do
    echo 'Value of var2: ',$test->get_var2();

    We’re happy to help you here, but FWIW, you might get a better response to general PHP questions that are not really related to WP in a forum dedicated to helping people needing general PHP help. stackexchange.com or stackoverflow.com maybe?

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.