[wp-trac] [WordPress Trac] #57887: The WordPress core does not support calling non-static methods for hook filters and actions within a namespace
WordPress Trac
noreply at wordpress.org
Wed Mar 8 14:37:02 UTC 2023
#57887: The WordPress core does not support calling non-static methods for hook
filters and actions within a namespace
-------------------------------------+-------------------------------------
Reporter: markcarbonell2013 | Owner: (none)
Type: defect (bug) | Status: new
Priority: normal | Milestone: Awaiting Review
Component: General | Version: 6.1.1
Severity: blocker | Keywords: changes-requested
Focuses: rest-api, coding- | needs-refresh needs-patch needs-
standards | testing
-------------------------------------+-------------------------------------
Technical Data
Wordpress Version: 6.1.1
OS: Ubuntu 20.04
PHP Version: 8.0
Current Behavior:
Non-static methods cannot be called by the WordPress core when the class
is namespaced. Only static methods can.
Steps to reproduce:
1. Create a fresh wordpress installation
2. Install the WP Code Snippets Plugin
3. Create a new snippet that runs everywhere with the code written below.
4. Observe how an error ocurrs the moment you save and activate the
snippet.
{{{
namespace test;
class MyPlugin {
public function __construct() {
add_action('rest_api_init', [$this, 'do_something_static']);
add_action('rest_api_init', [$this, 'do_something_non_static']);
}
public function do_something_non_static() {
error_log("If you read this, calling " . __FUNCTION__ . " worked");
}
public static function do_something_static() {
error_log("If you read this, calling " . __FUNCTION__ . " worked");
}
}
new MyPlugin();
}}}
Expected behavior:
Both non-static and static methods can be called by WordPress regardless
of whether the class/instance they belong to is namespaced or not.
Consequences:
This bug forces developers who structure their code professionally with
namespaces to exclusively use static methods every time a new WordPress
action or filter hook is added. Subsequently, every other class method
used by those classes must be static too. Resulting in a class composed
primarily of static methods. Thereby forcing developers to violate the
Single Responsibility Principle of OOP https://medium.com/att-israel
/should-you-avoid-using-static-
ae4b58ca1de5#:~:text=Static%20methods%20are%20bad%20for,that%20simple%20for%20some%20languages
If the developer is unaware of the error, no logs are written to the log
files and no error messages are displayed in the frontend. Making this
error particularly hard to track.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/57887>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list