How to reference a function from a class in a different file which is also namespaced?
-
16-04-2021 - |
Domanda
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
}
Soluzione
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 );
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange