变量ambit和在php OO中发送参数

时间:2012-08-25 21:45:41

标签: php oop parameters scope

我对通过PHP OO页面使用参数非常困惑。 我正在关注创建框架的教程(就像Zend Framework一样);但是,我不明白的是发生这种情况时:

示例,索引:

// File: sourcefiles/index.php

define('DS', DIRECTORY_SEPARATOR);
define('ROOT', realpath(dirname(__FILE__)).DS );
define ('APP_PATH',(ROOT.'aplicacion'));

require_once APP_PATH. DS.'Config.php';
require_once APP_PATH. DS.'Request.php';
require_once APP_PATH. DS.'BootStrap.php';
require_once APP_PATH. DS.'Controller.php';
require_once APP_PATH. DS.'View.php';

try
{
    BootStrap::run(new Request());

我有:

 // File: sourcefiles/controladores/IndexController.php
 <?php
        class IndexController extends Controller
        {
            public function __construct() {
                parent::__construct();
            }

            public function indexAction() 
            {
                 $this->view->titulo='Homepage';
                 $this->view->contenido='Whatever';
                 $this->view->renderizar('index');   
            }
        }
   ?>

而且:

// file : sourcefiles/aplicacion/View.php
<?php

class View
{
    private $controlador;
    private $layoutparams;

    public function __construct(Request $peticion)
    {
        $this->controlador = $peticion->getControlador();
    }

    public function renderizar($vista,$item=false)
    {
        $rutaview = ROOT.'vistas'.DS.$this->controlador.DS.$vista.'.phtml';

        if (is_readable($rutaview))
        {
            include_once $rutaview;
        }
        else
        {
            throw new Exception('Error de vista');
        }
    }
}
?>

这是视图:

// file : sourcefiles/vistas/index/index.phtml

<h1>
    Vista index..
    <?php
    echo $this->titulo;
    echo $this->contenido;
    ?>
</h1>

现在我的问题是:

IndexController如何使用该行? $this->view->titulo = blabla; 视图类没有“titulo”属性;但是,我可以做到这一点。但这是一个奇怪的事情,如果我在调用$this->view->renderizar('index')之后这样做,我就会收到错误。

index.phtml文件如何知道这一点? echo $this->titulo;因为,没有包含或要求被叫,这让我感到困惑。

当我在文件中执行require或include调用时,必需或包含的文件知道调用者的变量?

如果有人可以向我解释这些,我会非常感激:D 或者链接我关于这个的官方信息的讨论,或者这是怎么称呼的?

1 个答案:

答案 0 :(得分:1)

includerequire行视为“复制并粘贴”从一个文件到另一个文件的代码。这不太准确,但它解释了这里的部分行为:

sourcefiles/aplicacion/View.php中,您在内部功能sourcefiles/vistas/index/index.phtml中加入View->renderizar。因此,index.phtml中的所有代码都会被加载,就像它在该函数中发生一样。这就是您可以访问$this的原因。

至于在你没有定义时引用$this->view->titulo,这就是PHP让你变得懒惰。就像任何一个变量一样,一个物体上的一个成员会在你提到它时立即生活,只有一个通知警告你可能犯了错误。