admin管理员组文章数量:1425879
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
}
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
}
Share
Improve this question
asked Jul 3, 2019 at 13:48
Abe CaymoAbe Caymo
2232 silver badges7 bronze badges
1 Answer
Reset to default 1Firstly, 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 );
}
}
本文标签: namespaceHow to reference a function from a class in a different file which is also namespaced
版权声明:本文标题:namespace - How to reference a function from a class in a different file which is also namespaced? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745345548a2654462.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论