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 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数