[英]Access $this within PHP callback function
在下面的代碼中,我正在努力尋找一種在回調函數'cb'中訪問對象引用變量$ this的方法。 我遇到了錯誤
致命錯誤:不在對象上下文中時使用$ this
我希望能夠從函數“ cb”中調用方法“ bold”。
<?php
class Parser
{
private function bold($text)
{
return '<b>' . $text . '</b>';
}
// Transform some BBCode text containing tags '[bold]' and '[/bold]' into HTML
public function transform($text)
{
function cb($matches)
{
// $this not valid here
return $this->bold($matches[1]);
}
$html = preg_replace_callback('/\[bold\]([\w\x20]*)\[\/bold\]/', 'cb', $text);
return $html;
}
}
$t = "This is some test text with [bold]BBCode tags[/bold]";
$obj = new Parser();
echo $obj->transform($t) . "\n";
?>
您有一個變量范圍問題:在cb
函數中,沒有外部變量/對象/等可見。
將函數更改為類方法:
class Parser
{
(...)
private function cb( $matches )
{
return $this->bold( $matches[1] );
}
(...)
}
然后以這種方式修改您的preg_replace_callback
:
$html = preg_replace_callback( '/\[bold\]([\w\x20]*)\[\/bold\]/', array( $this, 'cb' ), $text );
# ====================
作為替代方案(在PHP> = 5.4上),您可以使用匿名函數:
$html = preg_replace_callback
(
'/\[bold\]([\w\x20]*)\[\/bold\]/',
function( $matches )
{
return $this->bold( $matches[1] );
},
$text
);
這對你有用嗎?
public function transform($text)
{
$html = preg_replace_callback('/\[bold\]([\w\x20]*)\[\/bold\]/', array($this, 'bold'), $text);
return $html;
}
您可能需要將更多的邏輯移至bold
函數,因為在這種情況下它將獲得匹配的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.