1

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
}

1 Answer 1

1

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 );
    }
}
4
  • I got a 'using $this when not in object context' , maybe a problem on how I instantiate the class? I currently use a pattern where I instantiate the class inside the file which looks like 'class::instance();' . Don't know if that helps
    – Abe Caymo
    Commented Jul 4, 2019 at 13:19
  • I've updated my answer. Commented Jul 4, 2019 at 13:35
  • finally got it. your initial answer was correct all along. forgot I was calling a function using $this inside the static method
    – Abe Caymo
    Commented Jul 5, 2019 at 6:43
  • It's fine for it to not be static, I just made the assumption that it was based on the question. The updated answer covers both situations. An important thing to keep in mind that passing functions to callbacks like this, as well as action hooks, is a standard PHP feature and will all follow the same rules: php.net/manual/en/language.types.callable.php Commented Jul 5, 2019 at 6:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.