【发布时间】:2017-10-02 10:46:36
【问题描述】:
感谢您检查这个问题:我正在编写一个 WordPress 主题,并且我想使用面向对象的编程来使该类可重用于我正在创建的多个元框。但是,我在尝试使用变量连接到我的函数名称时遇到错误。请帮我节省一些时间,我在文档和PHP: Variable in a function name 中找不到任何东西
class custom_metabox
{
private $cm_name_id;
private $cm_name;
private $cpt_name;
function __construct( $cm_name_id, $cm_name, $cpt_name ) {
$this->cm_name_id = $cm_name_id;
$this->cm_name = $cm_name;
$this->cpt_name = $cpt_name;
add_action( 'add_meta_boxes', array( $this, $cm_name_id . '_add_metabox_box' ) );
add_action( 'save_post', array( $this, $cm_name_id . '_box_save_postdata' ) );
}
/* Add metabox */
function $cm_name_id . _add_metabox_box() {
add_meta_box(
$cm_name_id . '_box_id', //ID for box
$cm_name, //Name for the box
$cm_name_id . '_box', //function for input
$cpt_name, //id for CPT
'normal', //location of input
'high' //priority
);
}
/* Prints the box content */
function $cm_name_id . _box( $post ) { ?>
<input class="widefat"
placeholder="option goes here"
name="<?php echo $cm_name_id; ?>_box_field"
id="<?php echo $cm_name_id; ?>_box_field"
value="<?php echo esc_html( get_post_meta( $post->ID, $cm_name_id . '_box_meta_value_key', true ) ); ?>" />
<?php }
/* Saves the value for the box content */
function $cm_name_id . _box_save_postdata( $post_id ) {
if ( array_key_exists('client_box_field', $_POST ) ) {
update_post_meta( $post_id, 'client_box_meta_value_key', $_POST['client_box_field'] );
}
}
}
【问题讨论】:
-
您不会将任何变量传递给您的构造函数。所以你的类变量没有任何价值。此外,您将在构造函数的前两行覆盖
$this->cm_name。我认为第一行应该是$this->cm_name_id = $cm_name_id而不仅仅是$this->cm_name.. 另外,你为什么这样做?总是使用相同的函数名称,然后像往常一样传递参数不是更简单吗? -
谢谢。我已经修改了。
-
仍然,您没有将任何值传递给您的构造函数。
$cm_name_id并且从未定义所有这些变量。所以你的类变量也没有任何值。