3

只是一个简单的问题,但我一直在研究一个小型 MVC 框架并注意到了一些东西。

例如:

--PHP文件--

class loadFiles{
        function __construct($file = NULL){
        include $file . '.php';
        }
}
$loadfiles = new $loadFiles('crucialsettings');
echo $randomstring; //Throws an error

--crucialsettings.php--

<?php
    $randomstring = 'hello';
?>

我只是意识到包含在对象范围内的文件无法从全局范围访问。将文件包含在对象中以便可以全局访问的最佳方法是什么?

我希望能够:

$loadfiles->settings();
$loadfiles->classes();
$loadfiles->passwords();

我想构建一个处理全局文件包含的类。

4

2 回答 2

2

在 PHP 中包含或要求代码的位置无关紧要。解释器在它的第一个定义过程中是非常线性的,也就是说,它基本上会将所有包含/需要的文件按照读取方式的确切顺序压缩到一个大文件中。

关于这一点需要注意的一件事是范围确实发生了变化。但一切都适用于“全球”范围。您始终可以使用“global”关键字将全局范围中的某些内容导入当前范围,以便在使用之前声明一个变量。因此,当您想使用另一个脚本中的“全局”变量时,只需请求它即可。

一个小例子...

一个.php

include('b.php');
global $myVar;
echo $myVar;

b.php

include('c.php');

c.php

$myVar = 'Hello World';

解释器在第一次通过后看到的是这段代码

// In global scope
$myVar = 'Hello World'

// In a.php scope
global $myVar;
echo $myVar;

简而言之,从您的 php 文件中只需添加该行

global $randomstring;

包含criticalsettings.php 文件后,您的回声将起作用。

于 2012-12-31T03:32:20.700 回答
1

看来您的框架过于依赖非 OOP 的内部结构。这不是一种更可取的构建方式,但您可以通过循环浏览变量列表并使它们成为您的类/实例范围的一部分来做您想做的事情。这里一个相当有用的函数是get_defined_vars();

假设您有文件 a.php、b.php 和 c.php。每个看起来像这样:

一个.php<?php $a = "AAAAAA";

b.php<?php $b = "BBBBBBBBBB";

c.php<?php $c = "CCCCCCCCCCCCCCCCCCCCCCCCCCC";

class mystuff {
    function include_with_vars( $____file ) {

        // grab snapshot of variables, exclude knowns
        $____before = get_defined_vars();
        unset( $____before['____file'] );

        // include file which presumably will add vars
        include( $____file );

        // grab snapshot of variables, exclude knowns again
        $____after = get_defined_vars();
        unset( $____after['____file'] );
        unset( $____after['____before'] );

        // generate a list of variables that appear to be new
        $____diff = array_diff( $____after, $____before );

        // put all local vars in instance scope
        foreach( $____diff as $variable_name => $variable_value ) {
            $this->$variable_name = $variable_value;
        }
    }

    function __construct($file = NULL){
        $this->include_with_vars( "a.php" );
        $this->include_with_vars( "b.php" );
        $this->include_with_vars( "c.php" );
    }
}

$t = new mystuff();
echo "<PRE>"; 
print_r( $t );

该程序现在将从您的 include() 指令中获取局部变量并将它们放在类范围内:

mystuff Object
(
    [a] => AAAAAA
    [b] => BBBBBBBBBB
    [c] => CCCCCCCCCCCCCCCCCCCCCCCCCCC
)

换句话说,文件 a.php( $a) 中的局部变量现在是$t->a.

于 2012-12-31T05:21:46.977 回答