• Resolved ace0930

    (@ace0930)


    In the main plugin file, the callback function of the hook has to be like the below if I’m using namespace:

    
    namespace test;
    
    add_action('admin_menu', __NAMESPACE__ . '\function_name');
    

    But why if I include a file called load.php on the main plugin file, and it works like normal without mentioning the __NAMESPACE__?
    So it looks like this on the main plugin file now:

    
    require_once __DIR__ . '/includes/load.php';
    

    The load.php looks like the below and it works:

    
    namespace test;
    
    add_action('admin_menu', 'function_name')
    

    But why if I use the exact same code from load.php on the main plugin file and it won’t work until I make it like:

    
    namespace test;
    
    add_action('admin_menu', __NAMESPACE__ . '\function_name');
    
Viewing 4 replies - 1 through 4 (of 4 total)
  • Dion

    (@diondesigns)

    I don’t think you understand how namespaces work. I’ll let you do some research to understand why this is true, but the following line will work in all your code as long as the function_name function is defined in the test namespace:

    add_action('admin_menu', '\test\function_name');

    If you require further assistance, I suggest that you ask your questions where PHP coding is discussed, such as StackExchange. In the meantime, if you are having difficulty using namespaces, perhaps you shouldn’t be using them.

    Thread Starter ace0930

    (@ace0930)

    @diondesigns Thanks.

    Tonya Mork

    (@hellofromtonya)

    Hello @ace0930,

    Appears the function named function_name() is located in the global namespace, rather than in the test namespace.

    How to find out:

    • Locate where the function exists in the code.
    • Scroll to the top of that file.
    • Is the test namespace defined in that file?

    The PHP manual has some examples to help you.

    Thread Starter ace0930

    (@ace0930)

    @hellofromtonya Appreciate your guideline! Thank you so much

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘namespace not working correctly’ is closed to new replies.