簡體   English   中英

為什么我的本地 PHP 函數看不到 $test 變量,如何獲取它的值?

[英]Why can't my local PHP function see the $test variable, and how can I get its value?

我正在使用 PHP HereDoc 和 NowDoc 語句在我的網站中構建網頁,HereDocs 用於需要將 PHP 變量值替換到網頁中的部分,NowDocs 用於使用$字符指定 jQuery 的部分我的 JavaScript 中的語句和 jQuery 對象變量。 然而,這使得我的 HTML、CSS 和 JavaScript/jQuery 難以閱讀和維護。

為了解決這個問題,我想我會寫一個替換函數來執行 HereDoc 語句所做的 PHP 變量替換,但是對於用字符串表達式或 NowDoc 語句分配值的變量。 這樣,字符串中${ variable-name }指定的 PHP 變量將被替換為它們的值,並且 jQuery 語句和$前綴變量的值應該是 jQuery 對象不會替換 PHP 變量,否則通常會導致如果沒有名稱與 jQuery 語句或變量名稱匹配的 PHP 變量,則會出現 PHP 編譯器錯誤,或者在名稱匹配時出現運行時邏輯錯誤。

這是我的代碼和一個測試 NowDoc:

  • 將包含${test} PHP 變量的長字符串分配給 PHP 數組變量中的元素,然后
  • 將數組作為參數傳遞給我的 NowHereDoc 函數以執行 PHP 變量/值替換。

但是,當我運行以下代碼來構建我的網頁時,$test PHP 變量在函數內部不可見,並且替換為 NULL 而不是所需的值。

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <?php // // PHP // function NowHereDoc( &$_array_ ) { // By Ref array parameter minimizes data movement when calling this function. $_l_ = count( $_array_ ); $_s_ = $_array_[ $_l_ - 1 ]; // Get the last element's string value. // Find each ${...} and substitute the variable's value ... $_i1_ = 0; while( ( $_i1_ = strpos( $_s_, '${', $_i1_ ) ) !== FALSE ) { // Get index of start of a variable name specified // by ${...} or FALSE when there aren't any {more}, // then stop looping. $_i2_ = strpos( $_s_, '}', $_i1_ ); // Get index of end of the ${...} just found. $_l_ = $_i2_ - $_i1_ + 1; // Get length of ${...}. $_var_ = substr( $_s_, $_i1_, $_l_ ); // Get the variable's name as a string. $_v_ = str_replace( [ '{', '}' ], '', $_var_ ); // Remove { and } from the variable name. $_val_ = "$_v_"; // Get the value of the specified variable -- this // doesn't find the variable, instead returns NULL! // Substitute the variable's value into the original string, $_s_ // $_s_ = substr_replace( $_s_, $$_var_, $_i1_, $_l_ ); // Replace the single occurance of the variable // with its value. This could to replace occurances // not with in comments, not yet implemented in // function. $_s_ = str_replace( $_var_, $_val_, $_s_ ); // Replace all occurances of the variable with its // value. } // End of while( ( $_i1_ = strpos( $_s_, '${', $_i1_ ) ) !== FALSE ) ... $_array_[ $_l_ - 1 ] = $_s_; // Set the last element's string value to the // updated string in $_s_. } // No Variable substitutions allowed in a NowDoc. $strMAINs[] = <<<'MAIN' <!-- ====================================================== ====================================================== = = HTML - ${test} - This should be substituted with hi = ====================================================== ====================================================== --> <p>to be set by this following script</p> <script id="scriptId"> // // JavaScript! // // The following jQuery statement shouldn't be changed. // var $jQVar = $( 'p' ).html( 'there' ); </script> MAIN; // // PHP // $test = 'hi'; NowHereDoc( $strMAINs ); ?> <!-- HTML --> <b>Test of my PHP NowHereDoc function</b>

如何通過指定為字符串值的名稱訪問 PHP 變量,這些變量在調用 NowHereDoc 函數的函數中是全局的或局部的,而不必將它們作為參數傳入或在函數中將它們指定為全局變量? 我記得看到一個 PHP 庫函數可以返回一個給定其名稱作為字符串的值,但我不記得該函數的名稱。

謝謝

要將全局變量導入您的函數,您可以執行以下操作:

// global scope
$test = 'my string';

function myFunction() {
    global $test;
}

或者,如果您有一個匿名函數,您可以像這樣從父作用域中提取變量:

function myOuterFn() {
    $test = 'my string';
    $myInnerFn = function() use ($test) {
        echo $test;
    };
}

為了回應您的評論,如果您遍歷內容以將任何引用的變量提取到一個 var 名稱數組中,您可以遍歷該數組並從全局導入它們,如本示例所示: https : //3v4l.org/ rH8J0

雖然不是模板解決方案,可能會在以后出現,但我找到了get_defined_vars()函數,這是我記得看到的那部分,但不記得它的名字。 它獲取調用時在范圍內的已定義變量的列表。 或者,可以創建一個手動變量列表並將其傳遞給函數,因為get_define_vars()函數返回的已定義變量列表中的大多數變量都是不需要的。

function NowHereDoc(  &$_vars_, &$_array_ ) { // a by-ref array of variables and their values from the caller's scope.
                                              //
                                              // a by-ref array specifying the web-content as a string that
                                              // contains one or more PHP variables in the ${...} format who's
                                              // values are to be substituted for the variable name.
                                              //
                                              //  & By-Ref prefix minimizes data movement when calling this function.
                                              //

    $_l_ = count( $_array_ );
    $_s_ = $_array_[ $_l_ - 1 ]; // Get the last element's string value.

    // Find each ${...} and substitute the variable's value ...

    $_i1_ = 0;
    while( ( $_i1_ = strpos( $_s_, '${', $_i1_ ) ) !== FALSE ) { // Get index of start of a variable name specified
                                                                 //  by ${...} or FALSE when there aren't any {more},
                                                                 // then stop looping.

        $_i2_  = strpos( $_s_, '}', $_i1_ );                     // Get index of end of the ${...} just found.
        $_l_   = $_i2_ - $_i1_ + 1;                              // Get length of ${...}.
        $_var_ = substr( $_s_, $_i1_, $_l_ );                    // Get the variable's name as a string.
        $_v_   = str_replace( [ '$', '{', '}' ], '', $_var_ );   // Remove { and } from the variable name.
        $_val_ = $_vars_[ $_v_ ];                                // Get the value of the specified variable.

        // Substitute the variable's value into the original string, $_s_

        // $_s_ = substr_replace( $_s_, $_val_, $_i1_, $_l_ );  // Replace the single occurance of the variable
                                                                 // with its value. This could to replace occurances
                                                                 // not with in comments, not yet implemented in
                                                                 // function.

        $_s_   = str_replace( $_var_, $_val_, $_s_ );            // Replace all occurances of the variable with its
                                                                 // value.

    } // End of while( ( $_i1_ = strpos( $_s_, '${', $_i1_ ) ) !== FALSE ) ...

    $_array_[ $_l_ - 1 ] = $_s_;                                 // Set the last element's string value to the
                                                                 // updated string in $_s_.

}

// No variable substitutions.
$strMAINs[] = <<<'MAIN'
<!-- 
=======================================================================
=======================================================================                     
=
= ${test1} ${test2} // ${test1} ${test2} should be substituted with hi there
=          
=======================================================================          
=======================================================================
-->
MAIN;

$test1 = 'hi';
$test2 = 'there';

$vars = get_defined_vars();
NowHereDoc( $vars, $strMAINs );

再次感謝馬特和 CBroe 的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM