【发布时间】:2015-04-22 01:02:39
【问题描述】:
我的班级中有两个职能部门,需要使用其中一个职能部门的信息来决定另一个职能部门。我虽然可以改变一个属性的值,就像它在 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();
【问题讨论】:
-
显示类定义是一个好的开始,但您能否也发布一些示例代码来说明您希望如何实例化和使用此类?
-
看来你要在
set_the_condition()中传一个参数,类似于set_the_condition($condition ) -
其余代码在哪里?你是如何调用这些方法的?
-
@Ja͢ck 我已经更新了上下文。关键是我不能在同一个函数中设置和使用条件(使用 WordPress 操作和过滤器),这就是为什么我认为它可以使用类属性来执行此操作。我的问题是 PHP 比 WordPress 相关的问题更多,只是指出我正在尝试更新一个属性以进一步使用它。
-
我猜这取决于首先调用哪个方法;怎么样,在
use_the_cart_condition()里面你总是打电话给$this->check_cart_for_condition();?
标签: php wordpress properties