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

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置