将PHP变量注入HTML代码
之前可能已经提出过这个问题,但我找不到一些初步搜索问题的答案,所以这里是:
我将PHP变量注入HTML的当前方法的一个非常简单的示例如下: HTML(file.php): <tag><?php echo $variable; ?></tag> PHP: $variable = "value"; ob_start(); include "file.php"; $results = ob_get_clean(); 这样就可以很好地实现正确的结果,但每次我必须复制并粘贴这三行以将变量注入我的HTML文件时,它会让我很烦.我可能希望在以后更改此注入功能的详细信息,并且它目前分散在我的代码中的几百个位置. 在一个完美的世界中,我会将这三行移动到一个单独的函数中,该函数将文件路径作为输入,并返回“已编译”的结果.但是,该函数将不再具有对调用范围的访问权限,并且我必须将变量作为另一个输入传递.我唯一能想到的就是: function injectVariables($filePath,array $variables) { //Built-in PHP function,extracts array key => value pairs into variable $key = value pairs in the current scope extract($variables); ob_start(); include $filePath; return ob_get_clean(); } 这当然可以完成工作,如果没有更好的解决方案,它将是我实施的,但对我来说似乎不太理想.它涉及每次运行时创建一个数组,只是为了遍历它并提取所有变量,这对我来说感觉有点不对. 有谁知道可能有用的任何其他方法? 解决方法
不确定你在问什么,但这是我的答案
我不知道您的代码的结构,但我希望您使用的是MVC方法(或者至少是处理类的方法),以便您可以执行以下操作: 在主控制器中,创建一个类变量,如viewData,它将是一个数组.你把所有你想要的东西放进去 $this->viewData['username'] = $username; $this->viewData['myArray'] = array('foo' => 'bar'); $this->viewData['menuSubview'] = 'path_to_menu_subview.php'; 然后,您创建一个渲染功能. public function render() { extract($this->viewData); ob_start(); include("myfile.php"); return ob_get_clean(); } 在myfile.php(使用HTML)中,您可以简单地执行到目前为止使用的内容 <div id="menu"><?php include($menuSubview);?></div> <p><?=$username;?></p> <p><?=$myArray['foo'];?></p> 整个代码可以是这样的. class Something { protected $viewData; protected $viewFile; public function logic() { $this->userProfile(); echo $this->render(); } public function userProfile() { $this->viewData['username'] = 'John The Ripper'; $this->viewFile = 'myFile.php'; } public function render() { extract($this->viewData); ob_start(); include($this->viewFile); return ob_get_clean(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |