简体   繁体   English

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

[英]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. 我尝试了很多搜索,但无法弄清楚为什么函数DoWordLink中的数组$ wordlinks没有携带函数__construct的值。 PHP class code as below: PHP类代码如下:

<?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? 你不是错过了这个“this->”构造吗? 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: 你可以使它成为该类的实际方法,并使用此方法调用它: 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: 更改DoWordLink函数,使其成为类的一部分,如:

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! 你需要使用object-accessor访问linkkeywords -method中的属性!

public function linkkeywords ($posts)
{

   // Here use $this->wordlinks not $wordlinks
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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