Kurt Bourbaki
Kurt Bourbaki

Reputation: 12596

Passing variables between objects using constructor

I want to create a $data variable in index.php, then create a new controller (ItemController) which should put something in $data and pass it back to index.php (which is the front controller).

I'm doing this, but it doesn't work.

ItemController.php

<?php

class ItemController {
    public $data;

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

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

?>

index.php:

<?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.
?>

How can I do? I'm trying to do something like Java Spring's controller method:

private function methodName(Model model) {
    String name = "James";
    model.add(name);
    return "templateName";
}

Upvotes: 0

Views: 111

Answers (1)

Eisa Adil
Eisa Adil

Reputation: 1733

It should be $this->data. Because you are referring to a variable in the object. So the code should be

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

Upvotes: 3

Related Questions