2017-04-11 61 views
1

編輯:這不是關於未定義變量的一般問題,而是關於這個特定的代碼示例,它沒有指定從哪裏拉動變量。

我正在嘗試使用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

這不是關於未定義變量的一般問題,而是關於這個特定腳本的問題。 –

回答

1

此行

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

相關問題