dongmou2389
dongmou2389
2011-06-21 20:49

PHP类:无法访问另一个函数中的数组

已采纳

I tried a lot of search but unable to figure out why array $wordlinks in function DoWordLink is not carrying values from function __construct. PHP class code as below:

<?php

class autolinkkeyword
{

    public $wordlinks = array();

    public function __construct(){
        $query = mysql_query("SELECT keyword FROM library");
                while ($row = mysql_fetch_array($query))
                {
                    $this->wordlinks [$row["keyword"]] = $row["keyword"];
                }
    }               

    public function linkkeywords ($posts)
    {                
            function DoWordLink($match)
            {
                $rpl=$match[1];
                if(isset($wordlinks[$rpl])) 
                {
                        $kword = $this->wordlinks[$rpl];
                        $rpl="<a class=\"keyword_link\" href=\"#\" onclick=\"popup('popUpDiv'); 
                                ajax_loadContent('kword', 'library.php?keyword=$kword')\">$kword</a>";
                        unset($this->wordlinks[$match[1]]);
                }
                return $rpl;
            }

            $wl=array_keys($this->wordlinks);           
            $pm="/((?<=\s|^)(?:" . implode('|',$wl) .")(?=\.|\!|\?|\,|\'|\s|$))/im";
            foreach($posts as $key => $mainbody)
            {
                $mainbody=preg_replace_callback($pm, 'DoWordLink', $mainbody)  ;    
                echo $mainbody;
            }

    }       
}
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • dongmeiran609914 dongmeiran609914 10年前

    You can make it an actual method of that class and call it using this method: http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback like:

    preg_replace_callback($pm, array($this, 'DoWordLink'), $mainbody);
    

    Change DoWordLink function so it is part of the class like:

    class autolinkkeyword
    {
      function DoWordLink($match)
      {
        $rpl=$match[1];
        if(isset($this->wordlinks[$rpl])) 
        {
          $kword = $this->wordlinks[$rpl];
          $rpl="<a class=\"keyword_link\" href=\"#\" onclick=\"popup('popUpDiv'); 
          ajax_loadContent('kword', 'library.php?keyword=$kword')\">$kword</a>";
          unset($this->wordlinks[$match[1]]);
        }
        return $rpl;
      }
    }
    
    点赞 评论 复制链接分享
  • dragon8002 dragon8002 10年前

    You need to access the property in your linkkeywords-method with the object-accessor, too!

    public function linkkeywords ($posts)
    {
    
       // Here use $this->wordlinks not $wordlinks
    }
    
    点赞 评论 复制链接分享
  • dongtao4890 dongtao4890 10年前

    Use the $this everywhere you refer to $wordlinks.

    $this->wordlinks
    
    点赞 评论 复制链接分享
  • dpbv85276 dpbv85276 10年前

    aren't you missing a "this->" construct here? if(isset($this->wordlinks[$rpl]))

    点赞 评论 复制链接分享

相关推荐