0

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";
}
3
  • 1
    Eisa Adil's answer is correct. Additionally: consider making your $data property private ( private $data; ) instead of public. Public means you can access the variable from outside the class aswell ( $controller->data[] = 'nonsense'; would work), which you probably don't want. Commented Dec 16, 2013 at 15:29
  • @DamienOvereem and what should I do to take $data in my index.php if $data is private? Should I put a getter method in my ItemController and call it with $controller->getData() ? Commented Dec 16, 2013 at 21:36
  • 1
    Yes, reason being that if you ever decide to change your class or the contents of the $data property, you can still make getData() return the same information, which then won't break your controllers. Although some people do things differently, I never allow direct access to my classes' properties. Commented Dec 17, 2013 at 8:03

1 Answer 1

3

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';
    }
Sign up to request clarification or add additional context in comments.

1 Comment

So "alert('$data[name]')" should be alert('$controller->data[name]'). Or use getter ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.