__CLASS__ vs $this
The difference between
add_filter( 'comments_open', array( __CLASS__, 'comments_open' ), 10, 2 ); and
add_filter( 'comments_open', array( $this, 'comments_open' ), 10, 2 ); lies in the way they reference the class and its methods.
In the first case, __CLASS__ is a magic constant in PHP that refers to the class name in which it is used. So, __CLASS__ will be replaced with the actual class name at runtime. This is useful when you want to reference a static method within the same class.
In the second case, $this refers to the current instance of the class. It is used to access non-static methods and properties within the class. When you use $this, you are referring to the specific instance of the class that the code is being executed in.
So, the difference is that __CLASS__ is used to reference a static method, while $this is used to reference a non-static method within an instance of the class.
Here’s an example to illustrate the difference:
class MyClass {
public function __construct() {
// Using $this to reference a non-static method
add_filter( 'some_filter', array( $this, 'nonStaticMethod' ) ); // Output: This is a non-static method.
}
public static function init() {
// Using __CLASS__ to reference a static method
add_filter( 'some_filter', array( __CLASS__, 'staticMethod' ) ); // Output: This is a static method.
}
public static function staticMethod() {
echo "This is a static method.";
}
public function nonStaticMethod() {
echo "This is a non-static method.";
}
}
// Using the class name to reference the static method outside of the class
add_filter( 'some_filter', array( 'MyClass', 'staticMethod' ) );
// Using the class name to reference non-static method outside of the class
$obj = new MyClass();
add_filter( 'some_filter', array( $obj, 'nonStaticMethod' ) );
In the example above, __CLASS__ is used to reference the static method staticMethod() within the MyClass class. On the other hand, $this is used to reference the non-static method nonStaticMethod() within an instance of the MyClass class.