我正在使用 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 库函数可以返回一个给定名称作为字符串的值,但我不记得函数的名称。
谢谢