我目前正在对使用 MVC 的小型个人框架进行一些升级。
它目前的工作方式是,当 Init.php 包含在某个文件中时,它不是寻找变量,而是获取文件的文本内容(实际源代码(并"剪切"变量。我相信这是非常非正统的,老实说,只是糟糕。
一位开发人员同事也开发了一个也使用 MVC 的框架,并且能够以正确的方式做我想做的事情。
<?php
require 'Init.php';
$page['id'] = 'index';
$page['name'] = 'Home';
这就是我们两个文件的样子,但是,如果我说,在 $page['name'] 元素上使用变量而不是字符串,页面的标题实际上是变量名称(想象一下"Sitename - $variable"(
我已经寻找了大约 2 天的答案,我找到了一个基本上使用 require_once 和 ob_get_contents 的有前途的答案,但是,我不想使用require_once。
我该如何做我的开发人员同事所做的工作?
编辑
这是我目前获取数组的尝试,它仅在使用require_once时才有效。
/************* CONTENT PARSING **************/
global $page;
$buffer = explode('/', $_SERVER['PHP_SELF']);
$filename = $buffer[count($buffer) - 1]; // index.php in our case
var_dump($page); // Dumps NULL
ob_start();
include($filename);
echo $page['id']; // Echoes nothing
echo ob_get_contents(); // Echoes nothing
echo $page['id']; // Dumps nothing
ob_flush(); // Returns nothing
var_dump($page); // Dumps nothing
编辑 2
以下是包含文件和声明变量的方式
config.php
和pageTpl.php
包含在Init.php
config.php
包含 $page
数组,并且包含在 pageTpl.php
index.php
包括Init.php
简而言之,我想分配给 $page
数组的 id
和 name
元素的值只能在您在index.php
上访问,我希望开发人员全局访问该变量。(包括 init.php
我尝试对每个文件运行var_extract($page)
,结果如下:
config.php(声明$page
数组的位置(:array ( 'id' => '', 'name' => '', ),
Init.php(包括config.php
(:array ( 'id' => '', 'name' => '', ),
索引.php(更改值的位置(:array ( 'id' => 'index', 'name' => 'Test', )
pageTpl.php (包含在 Init.php
中的文件,尝试访问 $page
数组(:
NULL
,所以在浏览了几次文档并阅读了一些框架的代码之后,我注意到获取所有这些变量的最终值的唯一方法是使用 PHP register_shutdown_function
,这是脚本执行完成后调用的函数,这意味着所有变量都被处理, 计算,因此只要它们是全局的,就可以从该函数访问所有函数。
例:
索引.php
<?
require 'Init.php';
$page['id'] = 'index';
$page['name'] = 'Home';
然后,在 Init 上.php我们做了所有复杂的框架,但我们也包括内核,它将包含关闭函数
初始化.php
<?
require 'inc/kernel.php';
new Kernel;
现在,当然是内核
内核.php
<?
class Kernel
{
public function __construct()
{
register_shutdown_function('Kernel::Shutdown'); // Registers shutdown callback
spl_autoload_register('Kernel::LoadMod'); // Not exactly sure why is this function necessary, but it is. All I know is that it tries to files of called classes that weren't included
}
static function Shutdown()
{
global $page;
var_dump($page); // Will print what we defined in the $page array
Module::LoadTpl($page); // We pass the $page array to the tpl module that will do the rest
}
}
模块.php
类模块{ 静态函数 LoadTpl($page( { var_dump($page(;也会打印$page,但现在我们不仅限于内核.php }}
然后,从Module
类中,您可以将$page
数组传递给其他类/文件。
当你定义一个带有索引的数组时,你需要以特定的方式完成它。
配置.php:
<?php
$page = array('id' => "", 'name' => "");
var_export($page);
?>
这将创建名为 $page
的数组,其索引为 id
和 name
,其值为 nothing。
现在,在索引.php中,可以分配值:
<html>
<body>
<pre>
<?php
include 'Init.php';
$page['id'] = basename($_SERVER['PHP_SELF']);
$page['name'] = 'Home';
var_export($page);
?>
</pre>
</body>
</html>
这应该会导致一个页面显示:
array ( 'id' => '', 'name' => '', )
array ( 'id' => 'index.php', 'name' => 'Home', )