在下面的代码中,我很难找到一种方法来访问回调函数'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
,因为在这种情况下它将获得一个匹配数组。