我很可能是走错了路,但我不知道如何纠正这一点。。。。如果有人能给我指出正确的方向,那就太好了。如果需要,很乐意提供更多细节。我的问题如下:
我有一个父类,一个需要访问一些父变量的子类,还有一个包含do\\u action调用的页面,就像这样
/****plugin ***/
class PARENT(
protected $pluginVersion;
protected $pluginOptions;
function __construct() {
$this->pluginVersion=\'1.5\';
$this->pluginOptions = get_option(\'option_name\',0);
add_action(\'choose_gateway\', array( $this, \'choose_gateway\'));
}
function choose_gateway(){
/**output some dropdown, select, whatever*/
echo $str;
}
}
class CHILD extends PARENT{
function __construct() {
$this->gatewayName = \'Cash on Delivery\';
/**plus some more other vars*/
/**
problem:
here i want to have access/use the variables set in the parent (i.e. $this->pluginOptions)
initially i thought i can just use
parent::__construct();
problem is though - if i do that - the "choose_gateway" action in parent is called twice....
***/
if(!is_admin()){
add_action(\'some_child_action\', array($this,\'some_child_action\'));
}
}
function some_child_action(){
}
/**some more functions**/
}
?>
/**** page***/
<?php
/*echo other stuff */
do_action(\'choose_gateway\');
/*more other stuff */
?>
我遇到的问题正如我在上面的代码中所评论的那样。我想我必须将“add\\u action”调用移出父构造,但我不确定,如果是这样,我不知道该放在哪里,因为它仍然可以通过“do\\u action”调用使用。。。
最合适的回答,由SO网友:fuxia 整理而成
我认为你的问题在于模式。您不应该创建控制器(主类)的子类,并且控制器不应该处理动作回调。
让控制器assign 对操作的回调。动作处理程序应该是单独的类。
基本示例:
namespace WPSE;
add_action( \'plugins_loaded\', function() {
new Controller;
});
class Controller
{
public function __construct()
{
$this->pluginVersion = \'1.5\';
$this->pluginOptions = get_option(\'option_name\',0);
$gateway = new Gateway( $this->pluginVersion, $this->pluginOptions );
add_action( \'choose_gateway\', array ( $gateway, \'choose_gateway\' ) );
$cash = new Cash( $this->pluginVersion, $this->pluginOptions );
add_action( \'get_cash\', array ( $cash, \'get_cash\' ) );
}
}
class Action_Handler
{
public function __construct( $version, $options ) {}
}
class Gateway extends Action_Handler
{
public function choose_gateway() {}
}
class Cash extends Action_Handler
{
public function get_cash() {}
}