我的课程中有两个功能,需要使用其中一个信息来做出另一个决定。我虽然可以通过将其设置为等于新值来改变属性的值,就像它在Javascript函数中工作一样,但这是一个很大的误解。如何在整个班级中更改属性的值?
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();
答案 0 :(得分:2)
当您调用操作或过滤器时,第二个值必须是可以在主题的functions.php文件中找到的方法的名称。您可以向文件添加自定义方法。
// In the functions.php file for the theme
function check_cart_for_condition() {
// get the session
global $session;
// initialize the $num var
$num = 0;
// 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.
$num = 1;
} elseif ( $cat_in_cart == 2 ) {
// Trying to update value of class property in
// order to use it in the next function.
$num = 2;
}
// This only needs to be for the next request since the hooks
// run back to back, add it to the session flash data
$session->set_flashdata( 'num', $num );
}
public function use_the_cart_condition() {
global $session;
// Retrieve Flashdata
$num = $session->flashdata( 'num' );
// If condition determined in upper function is met.
if ( $this->num == 1 ) {
// Do something
} elseif ( $this->num == 2 ) {
// Do something
}
}
现在只需将其添加到您需要的代码中:
add_action( 'woocommerce_cart_calculate_fees','check_cart_for_condition', 50 );
add_filter( 'wc_add_to_cart_message','use_the_cart_condition', 100, 2 );