简体   繁体   中英

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

    }       
}
?>

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

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

在你引用$ wordlinks的任何地方使用$ this。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM