saber
saber

Reputation: 5

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

    }       
}
?>

Upvotes: 0

Views: 498

Answers (4)

Justin
Justin

Reputation: 207

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

Upvotes: 1

Fidi
Fidi

Reputation: 5834

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
}

Upvotes: 0

Gustav
Gustav

Reputation: 1341

Use the $this everywhere you refer to $wordlinks.

$this->wordlinks

Upvotes: 0

r3c
r3c

Reputation: 498

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

Upvotes: 1

Related Questions