开发者

PHP class: Unable to access array in another function

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;
            }

    }       
}
?>


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;
  }
}


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


Use the $this everywhere you refer to $wordlinks.

$this->wordlinks


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜