我无法在静态方法中使用self
,它会向我显示以下错误消息:
Fatal error: Using $this when not in object context in C:\xampp\htdocs\wordpress\wp-content\plugins\dw-usercp\usercp.php on line 136
这是源代码:
class dw_usercp
{
public static function plugin_activated() {
self::create_plugin_pages();
}
public function create_plugin_pages() {
$pages = array(
'signin' => array(
'title' => __( 'Sign In', 'dw-usercp' ),
'content' => '[dwusercp-sigin-form]',
'option_id' => 'login_page'
),
'user-account' => array(
'title' => __( 'Your Account', 'dw-usercp' ),
'content' => '[dwusercp-info]',
'option_id' => 'user_account_page'
),
'edit-user-info' => array(
'title' => __( 'Edit User Info', 'dw-usercp' ),
'content' => '[dwusercp-edit-info]',
'option_id' => 'user_editinfo_page'
),
'profile' => array(
'title' => __( 'User profile', 'dw-usercp' ),
'content' => '[dwusercp-profile]',
'option_id' => 'profile_page'
),
'signup' => array(
'title' => __( 'Sign Up', 'dw-usercp' ),
'content' => '[dwusercp-signup-form]',
'option_id' => 'register_page'
),
'user-lost-password' => array(
'title' => __( 'Forgot Your Password?', 'dw-usercp' ),
'content' => '[dwusercp-password-lost-form]',
'option_id' => 'lost_password_page'
),
'user-password-reset' => array(
'title' => __( 'Pick a New Password', 'dw-usercp' ),
'content' => '[dwusercp-password-reset-form]',
'option_id' => 'password_reset_page'
)
);
foreach( $pages as $slug => $page ) {
$query = new WP_Query( 'pagename=' . $slug );
if ( ! $query->have_posts() ) {
// Add the page using the data from the array above
$post_id = wp_insert_post(
array(
'post_content' => $page['content'],
'post_name' => $slug,
'post_title' => $page['title'],
'post_status' => 'publish',
'post_type' => 'page',
'ping_status' => 'closed',
'comment_status' => 'closed',
)
);
$this->update_plugin_option( $page['option_id'], $post_id ); // this is the line 136 that the error message says
}
}
}
/**
* Update plugin option
*
* @param string $field option id
* @param mixed $value option new value
* @return bool
*/
public function update_plugin_option( $field, $value ) {
$options = get_option("dw_usercp_options");
$options[$field] = $value;
update_option( "dw_usercp_options", $options );
}
}
$dw_usercp = new dw_usercp();
register_activation_hook( __FILE__, array( 'dw_usercp', 'plugin_activated' ) );
如何正确调用create_plugin_pages()
?
plugin_activated()
必须是静态的,如Wordpress所说
答案 0 :(得分:2)
在静态函数中,您不在该类的实例中。你可以:
create_plugin_pages
函数设为静态,并使用static调用它。plugin_activated
转换为非静态(MY VOTE)由于您在$this
内拨打create_plugin_pages
,因此静态选项无法使用。因此,您需要采取实施路线。
非静态
public function plugin_activated() {
$this->create_plugin_pages();
}
这是传递对象版本
public static function plugin_activated(dw_usercp $a_dw_usercp) {
$a_dw_usercp->create_plugin_pages();
}
答案 1 :(得分:2)
因为你正在使用" $ this"您在静态上下文中的变量(您是否阅读了错误消息?)
在静态上下文中,用于方法:
self::method(args)
;
或
self::$attr
表示变量(属性)
答案 2 :(得分:1)
$this->update_plugin_option( $page['option_id'], $post_id );
不是 self
,正如标题中所引用的那样。你应该使用:
self::update_plugin_option( $page['option_id'], $post_id );