How do I get the value of a variable inside another

77 views Asked by At

I'm trying to get the $pi1 and $pi2 variable values inside of the add_custom_price function, but nothing seems to be working.

I have looked at setting variables to be accessible from function classes but I'm not sure I understand how to access them correctly.

add_filter( 'gform_confirmation', array(gravity_pi,custom_confirmation), 10, 4 );
    class gravity_pi {
      public $pi1;
      public $pi2;


      public function custom_confirmation( $confirmation, $form, $entry, $ajax, $product_id, $pi1, $pi2 ) { 
          if( $form['id'] == '2' ) {
            $post = get_post( $entry['post_id'] );
            $this->pi1 = rgar( $entry, '20' );
            $this->pi2 = rgar( $entry, '21' );
            $exclude_list = array("pi24","pi64","pi65","pi66","pi67","pi68","pi69","pi70","pi71","pi72","pi73","pi74","pi75","pi76","pi77","pi78","pi79","pi80","pi81","pi82");
            if(!in_array($this->pi1, $exclude_list) && !empty($this->pi1)){
              $target_product_id = '86';
              $pid1 = '86';
            }else{
              $pid1 = preg_replace("/[^0-9,.]/", "", $this->pi1 );
            }
            if(!in_array($pi2, $exclude_list) && !empty($this->pi2)){
              $target_product_id = '87';
              $pid2 = '87';
            }else{
              $pid2 = preg_replace("/[^0-9,.]/", "", $this->pi2);
            }
            $product_ids = ''.$pid1.','.$pid2.'';
            $url = 'https://*****.com/cart/?add-to-cart='.$product_ids.'';
            $confirmation = array( 'redirect' => $url );
          }
          return $confirmation;
      }

      public function add_custom_price( $cart_object, $entry,$form, $field, $input_id ) {

          foreach ( $cart_object->cart_contents as $key => $value ) {

              if( 86 == $value['data']->id ) {

                  $value['data']->set_price(  $this->pi1 );

              }
              if( 87 == $value['data']->id ) {

                  $value['data']->set_price( $this->pi2 );

              }

         }
      }
    }
    add_action( 'woocommerce_before_calculate_totals', array(gravity_pi,add_custom_price));
2

There are 2 answers

0
waterloomatt On

When you're setting the class properties (pi1 & pi2) you need to reference them in the same way you access them. Ex.

<?php
...
$this->pi1 = rgar($entry, '20');

Change all references (except where you declare them) of $pid1 to $this->pid1. Do this for $pid2 too.

Check this video out - https://www.youtube.com/watch?v=4c4nP7GLL1c

0
Deepansh Sachdeva On

You need to use $this to get/set any property in the class.

// set pi1 property value
$this->pi1 = 10;

//print/get property value
echo $this->pi1;