OOP PHP. How to selectively call a specific method defined in a class constructor?

I am learning Wordpress Multisite OOP code , and since I am pretty new to OOP , now I am in a situation where I cannot seem to decide on my own.

In particular, I create several classes for creating administration pages (both at the network level and at the level of subsidiary sites) using the OOP approach . Here is my simplified code:

class AdminPage {

    public function __construct( $args ) {
        add_action( 'admin_menu', array( $this, 'add_admin_page' ) );
    }

    public function add_admin_page() {
        add_menu_page( // arguments );
    }

}

class AdminNetworkPage extends AdminPage {

    public function __construct( $args ) {
        add_action( 'network_admin_menu', array( $this, 'add_admin_page' ) );
     }

}

The code works, but as you can see, I need to extend the AdminPage class for the sole purpose of changing the hook in the constructor (I need it admin_network_menufor admin pages at the network level instead admin_menu).

? , , , ?

, ($page = new AdminPage), (, $page->add_admin_page()) , add_menu_page is undefined... .

+4
1

- :

class AdminPage {

    public function __construct( $args, $networkPage = false ) {

        if($networkPage) {

            add_action( 'network_admin_menu', array( $this, 'add_admin_page' ) );

        } else {

            add_action( 'admin_menu', array( $this, 'add_admin_page' ) );

        }

    }

    public function add_admin_page() {

        add_menu_page( // arguments );

    }
}

, , , .

$page = new AdminPage($args);
$networkPage = new AdminPage($args, true);

, , ; , , , - ( ), .

0

Source: https://habr.com/ru/post/1687017/


All Articles