above code does not works for me, is not correct or any mistake from
my side?
And it didn’t work for me either. Because it throws this fatal error:
PHP Fatal error: No code may exist outside of namespace {} in …
And that’s because the PHP manual says:
No PHP code may exist outside of the namespace brackets except for an
opening declare statement.
So your code could be fixed in two ways:
-
Use the non-bracketed syntax.
<?php namespace NS; class MyClass { public function __construct() { add_action( 'init',array( $this, 'getStuffDone' ) ); } public function getStuffDone() { // .. This is where stuff gets done .. } } $var = new MyClass();
-
Put global code (or the
$var = new MyClass();
) inside a namespace statement (namespace {}
) with no namespace. Note though, that you need to useNS\MyClass
instead of justMyClass
.<?php // No code here. (except `declare`) namespace NS { class MyClass { public function __construct() { add_action( 'init',array( $this, 'getStuffDone' ) ); } public function getStuffDone() { // .. This is where stuff gets done .. } } } // No code here. (except another `namespace {...}`) namespace { $var = new NS\MyClass(); } // No code here. (except another `namespace {...}`)
UPDATE
Ok, this is what I have in wp-content/themes/my-theme/includes/MyClass.php
:
<?php
namespace NS;
class MyClass {
public function __construct() {
add_action( 'init', array( $this, 'getStuffDone' ) );
add_filter( 'the_content', array( $this, 'test' ) );
}
public function getStuffDone() {
error_log( __METHOD__ . ' was called' );
}
public function test( $content ) {
return __METHOD__ . ' in the_content.<hr>' . $content;
}
}
$var = new MyClass();
And I’m including the file from wp-content/themes/my-theme/functions.php
:
require_once get_template_directory() . '/includes/MyClass.php';
Try that out and see if it works for you, because it worked well for me:
-
You’d see
NS\MyClass::test in the_content.
in the post content (just visit any single post). -
You’d see
NS\MyClass::getStuffDone was called
added in theerror_log
file orwp-content/debug.log
if you enabledWP_DEBUG_LOG
.