在 PHP 回调函数中访问 $this
Access $this within PHP callback function
在下面的代码中,我努力寻找一种方法来访问回调函数中的对象引用变量 $this 'cb'。我收到错误
Fatal error: Using $this when not in object context
我希望能够从函数 '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
函数内部没有可见的外部 variable/object/etc。
将您的函数更改为 class 方法:
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
,因为在这种情况下它将获得一组匹配项。
在下面的代码中,我努力寻找一种方法来访问回调函数中的对象引用变量 $this 'cb'。我收到错误
Fatal error: Using $this when not in object context
我希望能够从函数 '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
函数内部没有可见的外部 variable/object/etc。
将您的函数更改为 class 方法:
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
,因为在这种情况下它将获得一组匹配项。