问题
This is a continuation of this question. When the class is extended, it refers to the original class method. The echoed class name in the created page should be AnotherAdminPage which is the extended class name.
/*
Plugin Name: static method callback demo
*/
class AnotherAdminPage extends AdminPageClass {
}
add_action('admin_menu', AnotherAdminPage::_admin_menu());
class AdminPageClass {
static function _admin_menu() {
$class_name = get_class();
$classinstance = new $class_name();
return array(&$classinstance, "admin_menu");
}
function admin_menu() {
add_options_page(
'Sample Admin Page Class',
'Sample Admin Page Class',
'manage_options',
'sample_admin-page_class',
array(&$this, 'admin_page'));
}
function admin_page() {
?>
<div class="wrap">
<p><?php echo get_class(); ?></p>
</div>
<?php
}
}
It works by redefining the methods in the extended class but it becomes somewhat pointless to extend it in that case.
class AnotherAdminPage extends AdminPageClass {
static function _admin_menu() {
$class_name = get_class();
$classinstance = new $class_name();
return array(&$classinstance, "admin_menu");
}
function admin_page() {
?>
<div class="wrap">
<p><?php echo get_class(); ?></p>
</div>
<?php
}
}
So is there a more elegant way of doing this?
回答1:
Use get get_called_class instead of get_class. http://php.net/manual/en/function.get-called-class.php . Then you don't need to redefine the _admin_menu function
回答2:
You should use get_called_class (PHP 5.3)
EDIT :
If you don't have PHP 5.3, you should read this
PHP get_called_class() alternative
回答3:
I found it by myself that this works.
/*
Plugin Name: extended class method as a callback demo
*/
class AnotherAdminPage extends AdminPageClass {
}
add_action('admin_menu', array(new AnotherAdminPage, "admin_menu"));
class AdminPageClass {
function admin_menu() {
add_options_page(
'Sample Admin Page Class',
'Sample Admin Page Class',
'manage_options',
'sample_admin_page_class',
array(&$this, 'admin_page'));
}
function admin_page() {
?>
<div class="wrap">
<p><?php echo get_class($this); ?></p>
</div>
<?php
}
}
来源:https://stackoverflow.com/questions/12820728/passing-extended-class-method-as-a-call-back-function-in-wordpress