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

在一个PHP类中的不同函数之间共享变量,php,wordpress,Php,Wordpress,我目前正在制作一个可湿性粉剂的小部件,我被困于此。我想把一个变量从一个函数传递到另一个函数。这些函数在同一个类中 class jpen_Custom_Form_Widget extends WP_Widget { public function __construct() { $widget_options = array( 'classname' => 'custom_form_widget', 'descriptio

我目前正在制作一个可湿性粉剂的小部件,我被困于此。我想把一个变量从一个函数传递到另一个函数。这些函数在同一个类中

     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'];
          }
            //...
        }
    }

创建一个类变量,并将其值设置为
$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'];

    }
}

通常的方法是将变量转换为类级变量。(在这种情况下,它可能是私有的)。当然,为了让deliver_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'];
      }
        //...
    }
}

为什么不让
$instance
成为类的成员呢?您可以让它成为类的属性,也可以像正常情况一样传递依赖项。如果将其设置为属性,则可能需要检查它是否在
deliver\u-mail
方法中设置。如果在form()函数之前执行了deliver\u-mail()函数,我该怎么办?@J.Domino您必须在deliver\u-mail()函数中编写一些代码来检查变量是否已填充,如果未填充,则抛出错误。或者,重新设计代码以更好的方式工作-我不知道上下文,但是可能deliver_mail()函数可以直接接受值,或者您可以接受构造函数中的值(因此在第一次创建对象时它就在那里),或者其他什么。在不知道用例等的情况下很难说什么是最好的,但这些都是您的一些选择。这是deliver_mail()函数-。它通过PHPMailer发送电子邮件。form()方法是widgets部分中的一个表单,用户可以使用它来填写电子邮件收件人。那么form()方法没有直接调用deliver\u mail()函数本身的原因是什么呢?你还没有给我一个完整的背景。不过我想我不需要它。我已经回答了别人提出的问题。这是否适合您的场景设计是另一个问题。我已经给了你一些关于如何重新设计它的想法…你需要仔细考虑你的用例和你需要经历的过程,并适当地构造你的代码,以便在没有地址的情况下它不能发送电子邮件。谢谢你的回答!一般来说,如果答案中包含对代码意图的解释,以及在不介绍其他代码的情况下解决问题的原因,那么答案会更有帮助。对不起,谢谢你,我以后也会处理这个问题。。。