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.

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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装