undefined variable $ parser using s9e \ TextFormatter

undefined variable $ parser using s9e \ TextFormatter

问题描述:

编辑:这不是关于未定义变量的一般问题,而是关于这个特定的代码示例,它没有指定从哪里拉动变量。

我正在尝试使用s9e \ TextFormatter设置标记的HTML白名单,如文档here

这里是我的代码:

use s9e\TextFormatter\Configurator; 

function htmlFormat() 
{ 
    $configurator = new Configurator; 
    $configurator->plugins->load('HTMLElements'); 

    $configurator->HTMLElements->allowElement('b'); 
    $configurator->HTMLElements->allowAttribute('b', 'class'); 
    $configurator->HTMLElements->allowElement('i'); 

    // Get an instance of the parser and the renderer 
    extract($configurator->finalize()); 

    $text = '<b>Bold</b> and <i>italic</i> are allowed, but only <b class="important">bold</b> can use the "class" attribute, not <i class="important">italic</i>.'; 
    $xml = $parser->parse($text); 
    $html = $renderer->render($xml); 
} 

htmlFormat(); 

然而变量$parser$renderer在该示例代码从未定义。我不知道如何将它们整合到这个代码中,是吗?

+2

'$ parser'&'$ renderer'可以是任何东西。也许回顾一下你从这个复制过来的代码来理解这些变量究竟是什么。 – Augwa

+1

[PHP的:“注意:未定义的变量”,“注意:未定义的索引”和“注意:未定义的偏移量”)可能的重复(http://stackoverflow.com/questions/4261133/php-notice-undefined-variable- notice-undefined-index-and-notice-undef) – Qirel

+0

这不是关于未定义变量的一般问题,而是关于这个特定脚本的问题。 –

此行

extract($configurator->finalize()); 

定义这些变量。这是因为extract()将“从数组导入变量到当前符号表中1(参考the PHP documentation example可能有助于理解这一点)。看的docblock为Configurator::finalize()

/** 
* Finalize this configuration and return all the relevant objects 
* 
* Options: (also see addHTMLRules() options) 
* 
* - addHTML5Rules: whether to call addHTML5Rules() 
* - finalizeParser: callback executed after the parser is created (gets the parser as arg) 
* - finalizeRenderer: same with the renderer 
* - optimizeConfig: whether to optimize the parser's config using references 
* - returnParser:  whether to return an instance of Parser in the "parser" key 
* - returnRenderer: whether to return an instance of Renderer in the "renderer" key 
* 
* @param array $options 
* @return array One "parser" element and one "renderer" element unless specified otherwise 
*/ 

2

这些最后两个选项(returnParserreturnRenderer)默认为true。

尝试运行这些行(配置配置实例后):

extract($configurator->finalize()); 
echo 'typeof $parser: '.get_class($parser).'<br>'; 
echo 'typeof $renderer: '.get_class($renderer).'<br>'; 

这应该产生这样的文字:

的typeof $解析器:S9E \的TextFormatter \分析器

的typeof $渲染器:s9e \ TextFormatter \ Renderer \ XSLT


http://php.net/extract

https://github.com/s9e/TextFormatter/blob/master/src/Configurator.php#L223