PHP中的简单视图函数


Simple view function in PHP

我做了一个简单的博客与MVC模式在php基于一些net.tutplus.com教程。我对php一窍不通,所以请帮助我理解它是如何工作的。

我在这里把它分解成几个简单的文件。3个文件,index。php index。view。php和function。php我想知道的是为什么我要把$data数组作为view函数的第二个参数来传递才能在index。view。php中访问它?如果我把$data作为我的视图函数的第二个参数,我得到未定义的变量,不能访问$data在我的index.view.php页面。

index . php

<?php
require('function.php');    
$data = array('item0', 'item1', 'item3');    
view('index', $data);

index.view.php

<?php
    foreach($data as $item) {
        echo $item;
    }
?>

function.php

function view($path, $data) {
    include($path . '.view.php');
}

我在这里有点困惑,因为每当我从视图函数中删除$data变量作为第二个参数,并在我的索引文件中替换视图('index', $data);include('view.index.php'); $data变量正在像预期的那样从index.php传递到index.view.php。

但是当我把没有$data参数的视图函数放回去时,我得到了未定义的变量数据。我认为我的视图函数做了完全相同的包括('view.index.php');?

希望这是有意义的,有人可以解释给一个新手是怎么回事,否则我会试着重新表述这一点

把include看作是复制和粘贴调用include的代码体。

如果你复制粘贴所有包含和要求的代码体,你会得到这个:

function view($path, $data) {
    foreach($data as $item) {
        echo $item;
    }
}  
$data = array('item0', 'item1', 'item3');
view('index', $data);

该代码应该可以工作,但是如果您从view()函数中删除$data参数,您将得到不同的东西:

function view($path) {
    // $data doesn't exist here, not local to the function.
    // The foreach() loop therefore is trying to access $data variable which doesn't exist.
    foreach($data as $item) {
        echo $item;
    }
}
$data = array('item0', 'item1', 'item3');    
view('index');

我认为我的视图函数做的完全一样包括(view.index.php);吗?

正如您所演示的,它不会。

<?php
$data = array('item0', 'item1', 'item3');    
include('view.index.php');

在这个例子中,view.index.php看到的变量作用域是{$data}

<?php
$foo = "hello world"; // note this extra variable
$data = array('item0', 'item1', 'item3');    
view('index', $data);
function view($path, $data) {
    include($path . '.view.php');
}

在这个例子中,view.index.php看到的变量作用域是{$path, $data}。这是因为include发生在函数的作用域中。

<?php
$data = array('item0', 'item1', 'item3');    
view('index');
function view($path) {
    include($path . '.view.php');
}

因此,在本例中,view.index.php的变量作用域是{$path}

您必须设置一个默认值来允许调用,如view('index');

function view($path, $data = array()) {
    // Do some stuff
    include($path . '.view.php');
}

如果你想让全局变量在你的函数中可见,使用global

function view($path) {
    global $data;
    include($path . '.view.php');
}