I have two functions within my class and need to use information from one to make a decision in the other. I though I could change the value of a property just like it works in Javascript functions by just setting it equal to a new value, but that’s a big misunderstanding. How can I change the value of a property throughout a class?
class Show_Or_Not {
public $num;
public function __construct() {
add_action( 'woocommerce_cart_calculate_fees', array( $this, 'check_cart_for_condition'), 50 );
add_filter( 'wc_add_to_cart_message', array( $this, 'use_the_cart_condition'), 100, 2 );
}
public function check_cart_for_condition() {
// Ton of code checking how often a certain category occurs in the cart.
if ( $cat_in_cart == 1 ) {
// Trying to update value of class property in
// order to use it in the next function.
$this->num = 1;
} elseif ( $cat_in_cart == 2 ) {
// Trying to update value of class property in
// order to use it in the next function.
$this->num = 2;
}
}
public function use_the_cart_condition() {
// If condition determined in upper function is met.
if ( $this->num == 1 ) {
// Do something
} elseif ( $this->num == 2 ) {
// Do something
}
}
}
$newClass = new Show_Or_Not();
When you call an action or a filter, the second value needs to be the name of a method that can be found in your theme’s functions.php file. You can add custom methods to the file.
Now just add this to your code where you need it: