使用包含文件

时间:2015-10-06 07:24:02

标签: php include return

我有两个 index.php ,两者都使用 bootstrap.php 。引导程序文件正在设置DI-Container,我需要在两个索引文件中访问此DI-Container。

首先,我在考虑在bootstrap.php中使用简单的return

bootstrap.php中

<?php
require __DIR__ . '/vendor/autoload.php';
$container = new League\Container\Container;
// add some services
return $container;

的index.php

<?php
$container = require __DIR__ . '/bootstrap.php';
$container->get('application')->run();

我在某处读到使用像这样的return语句是一个坏习惯。所以我想知道如何以简单正确的方式使index.php中的容器可以访问?

1 个答案:

答案 0 :(得分:0)

如果您包含已经拥有变量$container

的访问权限的文件,则无需返回

<强> bootstrap.php中

<?php
require __DIR__ . '/vendor/autoload.php';
$container = new League\Container\Container;
// add some services

<强>的index.php

<?php
require __DIR__ . '/bootstrap.php';
$container->get('application')->run();

更新(评论后):

<强> bootstrap.php中

<?php
require __DIR__ . '/vendor/autoload.php';
// add some services
return new League\Container\Container;

<强>的index.php

<?php
$container = require __DIR__ . '/bootstrap.php';
$container->get('application')->run();

另一个例子:

如果需要在返回之前在Container对象上添加服务,则可以使用静态助手类(仅作为示例),如果要避免使用全局变量:

class Context {
    private static $container = null;

    public static function getContainer() {
        return self::$container;
    }
    /* maybe you want to use some type hinting for the variable $containerObject */
    public static function setContainer( $containerObject ) {
        self::$container = $containerObject;
    }
}

<强> bootstrap.php中

<?php
require __DIR__ . '/vendor/autoload.php';
// require the Context class, or better get it with your autoloader
Context::setContainer( new League\Container\Container );
// add some services
Context::getContainer()->addMyService();
Context::getContainer()->addAnotherService();

//if you want to, you can return just the container, but you have it in your Context class, so you don't need to
//return Context::getContainer();

<强>的index.php

<?php
require __DIR__ . '/bootstrap.php';
Context::getContainer()->get('application')->run();