I have a problem with calling function using alto routing. On index.php I I have my route that calls function that is in another file (test.php) and those two files are in the same directory (root). I get no response, but when I put that function from test.php to index.php where are my routes then it works and I need that function to work in test.php file. I tried putting 'require(index.php)' in test.php file but it doesn't work. Any help is appreciated if someone knows workaround for this. Here is my code.
index.php
<?php
require 'vendor/autoload.php';
$router = new AltoRouter();
$router->map('GET','/test', 'test.php', 'testfunction'); // HERE IS THAT ROUTE!!!
$match = $router->match();
if ( is_array($match) && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
test.php
<?php
require 'index.php';
function testfunction()
{
echo "YES IT WORKS!";
}
This is speculative, since I don't know AltoRouter, however if each page has it's own (single) specific function, you can return the function as a closure:
Closures were introduced in PHP 5.3. Then, your router would be something like:
This works because
requireandincludegive the return from the script:https://www.php.net/manual/en/function.include.php
See a sample in action here:
https://replit.com/@userdude/SimpleRouterReturnClosure#index.php
If you have 7.4, arrow functions make the syntax much simpler for the example: