简体   繁体   English

PHP函数内部的另一个函数[class]

[英]PHP function inside another function [ class ]

I have the following code, perform a global function within a class to fill the functions of wordpress, the problem is that the only way that I could get a variable public class is as follows 我有以下代码,在一个类中执行全局函数以填充wordpress的功能,问题是,我可以获得变量公共类的唯一方法如下

class Core {
 public $notice;
 function __construct(){
  $this->core_function();

 }
 function core_function(){
   global $globalvar;
   $globalvar = $this;
   function notice_global(){
    global $globalvar;

    return $globalvar->notice;

   } 
 }
 function set_notice(){
  $this->notice = array('Warning');
 }

}

$GP = new Core();
$GP->set_notice();
var_dump(notice_global());

Any other ideas or suggestions, this code is correct or not? 还有其他想法或建议,此代码正确与否?

As you said in the comments, you need global function due to wordpress hook method (for a plugin, I suppose). 正如您在评论中所说,由于wordpress hook方法(我想是一个插件),您需要全局功能。

This is not necessary: there is a way to pass an object method (not a whole object) to wordpress. 这不是必需的:有一种方法可以将对象方法(不是整个对象)传递给wordpress。

You can try in this way: 您可以通过以下方式尝试:

class Core {
    public $notice;

    function get_notice()
    { return $this->notice; }

    function set_notice()
    { $this->notice = array('Warning'); }
}

$GP = new Core();
$GP->set_notice();

add_action( 'save_post', array( $GP, 'get_notice' ) );

Or - for a better flexibility - in this way: 或者-为了获得更好的灵活性-以这种方式:

class Core {
    public $notice;

    function get_notice()
    { return $this->notice; }

    function set_notice()
    { $this->notice = array('Warning'); }

    function add_wp_action( $hook, $method )
    { add_action( $hook, array( $this, $method ) ); }
}

$GP = new Core();
$GP->set_notice();

$GP->add_wp_action( 'save_post', 'get_notice' );

By this way, you can directly set all your wp hooks in the class and call they directly with an object method, without using globals variables or function tricks. 这样,您可以直接在类中设置所有wp挂钩,并直接使用对象方法调用它们,而无需使用全局变量或函数技巧。

I'm not sure if I'm understanding you right, but notice_global can be moved out of that class. 我不确定我是否理解正确,但是notice_global可以移出该类。

Globals have scope outside of classes 全局变量在类之外

There is no need for these functions. 不需要这些功能。 You've defined $notice as public property. 您已将$notice定义为公共财产。 You can access it like this: $GP->notice ; 您可以这样访问它: $GP->notice ;

You might also want to read documentation on visibility of methods and properties. 您可能还想阅读有关方法和属性可见性的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM