php – How to make an object available after defined in static method

Question

In my plugin I’m calling a static method capture_details_form using and action hook upon a form submission which creates an object from a class Form to capture the form data and stores the object as $form_obj . I then want this object to be available to other objects to use the data for setting up db entries and interacting with APIs (for example).

For some reason I cannot access the $form_obj from other objects. Instead I get: PHP Notice: Undefined variable: form_obj in C:….

Example code:

class Form {
  // properties that hold form data
  public $var1;
  public $var2; //etc

  public function capture($form){
   // extracts form data and sets to object properties 

  }
}
class Order {
 public function init(){
  // do something with captured form data
  echo $form_obj->var1; //gives error 'Undefined variable: form_obj in C:\....'
 }
}
class Details {
 public function set_up_order(){
  $order = new Order
  $order->init();
 }
 public static function capture_form_data($form){
    $form_obj = new Form();
    $form_obj->capture($form);
    $this->set_up_order();
 }

}
add_action('form_submitted','capture_form_data');

I can’t figure out why the $form_obj is unavailable. I have considered using globals but many think that this is bad practice? Any help appreciated!

Edit

This has been closed at it’s not specific to wordpress, although if I wasn’t hooking to an action in wordpress I would have a solution (as I wouldn’t need to use a static method). Also this isn’t a 3rd party plugin its one that I’m writing.

Edit 2

I solved this problem myself by using static properties in the Form class instead (although I would still like to know more about object scope!):

class Form {
  // properties that hold form data
  public static $var1;
  public static $var2; //etc

  public function capture($form){
   // extracts form data and sets to Form class static properties
   self::$var1 = my_form_processing_func($form, 'field_1');
   self::$var2 = my_form_processing_func($form, 'field_2');

  }
}
class Order {
 public function init(){
  // do something with captured form data
  echo Form::$var1;
 }
}
class Details {
 public function set_up_order(){
  $order = new Order
  $order->init();
 }
 public static function capture_form_data($form){
    $form_obj = new Form();
    $form_obj->capture($form);
    $this->set_up_order();
 }

}
add_action('form_submitted','capture_form_data');

0
Macky McCormack 2 months 2022-10-05T11:58:00-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse