How to reference a function from a class in a different file which is also namespaced?

wordpress.stackexchange https://wordpress.stackexchange.com/questions/342089

  •  16-04-2021
  •  | 
  •  

Question

For example I am inside a file1.php with a namespaced class, like so:

<?php
namespace FrameWork\CPT;
class CPT{
      .....
public function register_custom_post_type()
{
$args = array(
'register_meta_box_cb' => //PROBLEM: How to reference from a different file 
                            which also contains a namespaced class
register_post_type('plugin-cpt', $args);
}

How do I access a public function from a namespaced class from file2.php?

<?php
namespace FrameWork\Helper;
class Metabox{
           .....
public function register_metaboxes()
{
 // I want to reference this function
}
Was it helpful?

Solution

Firstly, to do this the register_metaboxes() method needs to be static:

public static function register_metaboxes()
{

}

Then, for the callback you pass an array with the full class name including the namespace:

$args = array(
    'register_meta_box_cb' => [ 'FrameWork\Helper\Metabox', 'register_metaboxes' ],
);

If, for whatever reason, register_metaboxes() isn't static (i.e. you're using $this) then passing the class name isn't enough, you need to pass an instance of the class:

namespace FrameWork\CPT;

class CPT {
    public function register_custom_post_type()
    {
        $meta_box_helper = new FrameWork\Helper\Metabox();

        $args = [
            'register_meta_box_cb' => [ $meta_box_helper, 'register_metaboxes' ],
        ];

        register_post_type( 'plugin-cpt', $args );
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top