Best way to extends core classes in theme?

I need to add functions to my WP_User objects, to be used like this :

<?php
// in my templates :
$user = new User($id);
$user->sendHelloWorldEmail();

// in my functions.php
class User extends WP_User {
    public function sendHelloWorldEmail(){
        // do stuff ...
    }
}

My question is : what is the best way to overload Core Classes (WP_Post/WP_User…) ?

And : is it a good idea, or is there a better way to achieve this (with objects programming) ?

1 Answer
1

What you are doing will work, and is correct as far as the PHP goes.

Whether it is a good idea or not really depends on what you are doing specifically and whether you can do it with hooks– actions and filters– instead. If you can do it with hooks you probably should but your question doesn’t have detail enough to really allow for a great answer.

I don’t think that extending Core classes is “wrong” necessarily but you can set yourself up for higher than normal maintenance as your extended class may need to change if the parent does, so be aware. Its the “fragile base class” problem.

This is not really “overloading”, by the way, and in PHP “overloading” is not really that anyway.

Leave a Comment