使用构造函数在对象之间传递变量

时间:2013-12-16 15:07:46

标签: php variables model-view-controller

我想在 index.php 中创建一个$data变量,然后创建一个新的控制器( ItemController ),它应该在{{1}中添加一些内容并将其传递回index.php(这是前端控制器)。

我这样做,但它不起作用。

ItemController.php

$data

的index.php:

<?php

class ItemController {
    public $data;

    public function __construct($data) {
        $this->data = $data;
    }

    public function listItems() {
        $data = ['name' => 'James'];
        return 'templateName';
    }
}

?>

我该怎么办?我正在尝试像Java Spring的控制器方法那样做:

<?php

/* index.php is the front controller (something like a global controller
 * which routes all the requests to their relative controllers) */
require_once "controllers/ItemController.php";

// route the request internally
$uri1 = $_SERVER['REQUEST_URI'];

$data = Array();

if ($uri1 == '/sapienter/index.php') {
    $controller = new ItemController($data);

    $templateString = $controller->listItems();
    echo "<script type='text/javascript'>alert('$data[name]');</script>";
    // This alert results empty, while I want it to output "James"
}

// Here I'll use the templateString to redirect to my template page.
?>

1 个答案:

答案 0 :(得分:3)

应该是$this->data。因为您指的是对象中的变量。所以代码应该是

public function listItems() {
        $this->data = ['name' => 'James'];
        return 'templateName';
    }