douqiaoru2583 2012-02-10 14:42
浏览 72
已采纳

PHP OOP在create_function中调用私有函数作为回调

I have created a class extending SimpleXMLElement which loads an XML containing translations for a multilingual website. In this class are two private functions - get and translate. The former returns the translation contained in the node accessed by the xpath passed as an argument.

The latter replaces tag-like substrings in a string (eg. "Lorem ipsum #{dolor} sit amet, consectetur adipiscing elit.") with their translation obtained via the former function - the tag being a sort of xpath I process in my get() function.

I'm using preg_replace_callback in translate() - for I cannot pass a back reference as an argument to a function in preg_replace - to send matched occurrences to get(), which will replace them with the translation.

Here is a shortened version of my class :

$translation = new Translation('path_to_my_xml', null, true);

class Translation extends SimpleXMLElement {
    function get($xpath){
        // xpath is of the form 'parent_node/child_node'
        // After some processing and the wanted node being found - it returns the translation
    }

    function translate($string){
        $string = preg_replace_callback('/#\{([a-z0-9-\/]+)\}/', create_function('$matches', 'return $this->get($matches[1]);'), $string);
    }
}

Of course, I get a fatal error : using $this when not in object context, for the class hasn't been instantiated in my create_function call - I tried self::get($matches[1]) as well without success.
These functions cannot be public for my class being an extension of SimpleXMLElement, it requires the path to an XML in the constructor. So I can't do this : create_function('$matches', 'return Translation::get($matches[1]);').

I hope I made myself clear. The only workaround I see is passing the path to my XML in my translate() function and make it public, but this would be very inconvenient. Do you see any other way out ?

Thanks

  • 写回答

4条回答 默认 最新

  • doushi1912 2012-02-10 15:11
    关注

    Hang on, can't you just use an old style array PHP callback like this?

    function translate($string){
        $string = preg_replace_callback('/#\{([a-z0-9-\/]+)\}/', 
                                        array($this, 'translateCallback'), 
                                        $string);
    }
    
    public function translateCallback($matches)
    {
      return return $this->get($matches[1]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题