dr637349 2009-06-08 01:03
浏览 62
已采纳

PHP回调函数的可变范围

In response to another question I asked about regular expressions, I was told to use the preg_replace_callback function (PHP regex templating - find all occurrences of {{var}}) as a solution to my problem. This works great, but now I have a question relating to variable scope in callback functions.

The function that parses the text is part of a class, but the data that I want to use is stored locally in the function. However, I have found that I cannot access this data from inside my callback function. Here are the ways that I have tried so far:

  • Implement the callback as a private class function, passing '$this->callback_function' as the callback parameter (doesn't work, php has a fatal error)
  • Implement the callback inside the function that uses it (see example below) but this didn't work either because $newData is not in scope inside callback_function

Any ideas as to how I can access $newData inside my callback function, preferably without using globals?
Many thanks.

Example below for the second attempt (doesn't format properly when I put it after the bullet point)

public function parseText( $newData ) {
  ...
  function callback_function( $matches ) {
    ...  //something that uses $newData here
  }
  ...
  preg_replace_callback( '...', 'callback_function', $textToReplace );
}
  • 写回答

2条回答 默认 最新

  • duanlou7910 2009-06-08 01:12
    关注
    • Implement the callback as a private class function, passing '$this->callback_function' as the callback parameter (doesn't work, php has a fatal error)

    preg_replace_callback( '...', 'callback_function', $textToReplace );

    Change your call to be preg_replace_callback ('...', array($this, 'callback_function'), $textToReplace); while callback_function is a private method in your class.

    <?php
    
    class PregMatchTest
    {
    
        private callback_function ($matches)
        {
            // ......
        }
    
        public function parseText ($newData)
        {
            // ....
    
            preg_replace_callback( '...', array($this, 'callback_function'), $textToReplace );
        }
    
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法