0

Reading about passing variables to a user-defined function and it says you can access the variable outside the function using 'global' but going through an answer on SO, Matteo Tassinari suggests "avoid using globals at all and prefer passing as parameters"

This below is my index

<?php

$registry = new Registry(); <- need to pass this variable

$router->map('GET', '/', function ($controller = 'Home', $action = 'index') {

    if (method_exists($controller, $action)) {
        $controller = new $controller();
        $controller->$action();
    } else {
        echo 'missing';
    }
});

and I need to access the variable $registry which can be done easily by appending global to it but I would want avoid it and pass it as a parameter.

How do I pass $registry as a parameter?.

Mecom
  • 381
  • 3
  • 20
  • 2
    Use `use` ... https://blog.dubbelboer.com/2012/04/07/php-use-keyword.html, http://php.net/manual/en/functions.anonymous.php#example-165 – CBroe Jan 08 '18 at 12:16
  • Thank you ... How do I accept your answer? – Mecom Jan 08 '18 at 12:27

1 Answers1

1

You can try adding use ($registry) to the function

$router->map('GET', '/', function ($controller = 'Home', $action = 'index') use($registry) {
Zoe
  • 27,060
  • 21
  • 118
  • 148
leonardseymore
  • 533
  • 5
  • 20