dsfsdfsdfsdfsdf45454
2018-09-13 15:51
浏览 96
已采纳

Php为全局变量返回NULL

So I have the following code:

public function pcieh_shortcodes_init() {
    $data = $this->data;
    var_dump($data); //Return an array which is Expected       

    function pcieh_shortcode($atts = [], $content = null) {
         global $data;
         var_dump($data); //Return NULL
     }

    add_shortcode('pcieh', 'pcieh_shortcode');
}

When I call pcieh_shortcodes_int I expect the $data inside pcieh_shortcode to have the same value as outside $data since it's global but it returns NULL. Why is that and how can I fix it?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyudouchao6779 2018-09-13 17:22
    已采纳

    Instead of this

     public function pcieh_shortcodes_init() {
         $data = $this->data;
         var_dump($data); //Return an array which is Expected       
    
         function pcieh_shortcode($atts = [], $content = null) {
              global $data;
              var_dump($data); //Return NULL
          }
    
         add_shortcode('pcieh', 'pcieh_shortcode');
     }
    

    Why not this

    public function pcieh_shortcodes_init() {
        $data = $this->data;
        var_dump($data); //Return an array which is Expected       
        add_shortcode('pcieh', [$this,'pcieh_shortcode']);
    }
    
    public function pcieh_shortcode($atts = [], $content = null) {
        var_dump($this->data); //Return NULL
    }
    

    Then there is no need for global or any of the ugliness associated with it. It's perfectly acceptable to pass a class and method in as an array.

    Basically wordpress is using call_user_func to call this anyway.

    http://php.net/manual/en/function.call-user-func.php

    UPDATE

    I should have noted, in the original code in the question, even if you did get it to work, you have no reference to the actual instance of this class, so any value you set in data (after assign the short code, and global) would have likely been lost anyway. In other words you would lose the state of the current object and any data it contains.

    So by using the actual instance $this you can be sure you are actually dealing with the instance you want to.

    打赏 评论

相关推荐 更多相似问题