PHP - 将变量传递给index.php

时间:2016-06-17 09:43:53

标签: php oop

它是根目录中的index.php文件:

的index.php

<?php

require_once 'engine.php';
require_once 'startController.php';

$engine = new Engine('start');

?>
<html>
    <head>
        <title>

        </title>
    </head>
</html>

在引擎类中还有另一个对象

engine.php

class Engine
{
    puublic $controller = null;

    public function __construct($controller)
    {
        $controllerFile = $controller.'Controller';
        $this->controller = new $controllerFile('Page');
    }
}

和控制器类

startController.php

class startController
{
    public function __construct($text)
    {
        $variable = 'Start'.$text; // output "StartPage" because of $text val.
    }
}

问题是:如何将$variablestartController对象传递到 index.php ,并在title标记之间显示?

2 个答案:

答案 0 :(得分:0)

简化为:

<?php

$vars = array('title' => '');

function foo(&$vars) {
    $vars['title'] = 'Bar';
}

foo($vars);
?>
<html>
<title><?php echo $vars['title']; ?></title>
...

您可以将$ vars用作全局:

<?php

$vars = array('title' => '');

function foo() {
    global $vars;
    $vars['title'] = 'Bar';
}

foo();

但也许您最好使用控制器可访问的视图对象。

答案 1 :(得分:0)

您可以通过以下方法执行此操作:

<?php
class startController
{
    public $variable;
    public function __construct($text){
        $this->variable = 'Start'.$text; // output "StartPage" because of $text val.
    }

}

?>

<?php
class Engine
{
    public $controller = null;
    public $variable;

    public function __construct($controller)
    {
        $controllerFile = $controller.'Controller';
        $this->controller = new $controllerFile('Page');
    $this->variable = $this->controller->variable;
    }
}
?>

并在index.php中

<?php

require_once 'engine.php';
require_once 'startController.php';

$engine = new Engine('start');
echo $engine->variable;
?>

希望这可以帮助你:)