在一个类中的不同函数之间共享变量

时间:2018-11-11 19:00:24

标签: php wordpress

我目前正在制作WP小部件,并且对此感到困惑。我想将变量从一个函数传递给另一个函数。这些函数在同一类中。

     class jpen_Custom_Form_Widget extends WP_Widget {

      public function __construct() {
       $widget_options = array(
        'classname' => 'custom_form_widget',
        'description' => 'This is a Custom Form Widget',
        );

         parent::__construct( 'custom_form_widget', 'Custom Form Widget', $widget_options );

           add_action( 'wp_ajax_send_mail', array( $this, 'deliver_mail' ) );
           add_action( 'wp_ajax_nopriv_send_mail', array( $this, 'deliver_mail' ) );

          } 
         //...
        function deliver_mail() {     
          //How to access $instance['email'] value;
        }

        public function form( $instance ) { 

          $emailReceiver = '';
          if( !empty( $instance['email'] ) ) {
            $emailReceiver = $instance['email'];
          }
            //...
        }
    }

2 个答案:

答案 0 :(得分:0)

通常的方法是使变量成为类级别的变量。 (在这种情况下,它可能是私有的)。当然,为了使liver_mail()函数能够使用它,必须首先执行form()函数。

class jpen_Custom_Form_Widget extends WP_Widget {

    private $emailReceiver;

    function deliver_mail() {     
      //How to access $instance['email'] value;
      print_r($this->emailReceiver); //example of using the value
    }

    public function form( $instance ) { 

      $this->emailReceiver = '';
      if( !empty( $instance['email'] ) ) {
        $this->emailReceiver = $instance['email'];
      }
        //...
    }
}

答案 1 :(得分:-1)

制作一个类变量并将其值设置为$instance['email']以便在另一个函数中共享它。

class jpen_Custom_Form_Widget extends WP_Widget {

    // make a class variable
    public $var;

    function deliver_mail() {     
      //How to access $instance['email'] value;

      //Use is any where with $this
      var_dump($this->var);
    }

    public function form( $instance ) { 

      $emailReceiver = '';
      if( !empty( $instance['email'] ) ) {
        $emailReceiver = $instance['email'];
      }

        //set class variable value
        $this->var = $instance['email'];

    }
}