How to execute a require_once within a method of a function being passed as a parameter of another function?

Asked

Viewed 69 times

-2

I’m trying to understand and make a PHP router.

index php.

<?php

    require_once 'config.php';
    require_once 'router.php';
    
?>

config.php

<?php   

    error_reporting(E_ALL);
    ini_set('display_errors', true);
    date_default_timezone_set('America/Sao_Paulo');

?

php router.

<?php   
    
    require_once 'Rotas.php';
    
    $rota = new Rotas;
    
    $rota->get("/", function() {
        require_once 'home.php';
    });
    
    $rota->get("/contato", "ConTato@form");

?>

Routes.php (the Class)

<?php
        
    class Rotas {
        
        public function __construct() {}
        
        public function get (String $rota, $require = null){
            
            if ($_SERVER['REQUEST_URI'] === $rota) {
            
                if ( is_string($require) and $require !== "" ){
                    
                    $require = strtolower($require);
                    $require = explode('@', $require);
                    $class = ucfirst($require[0]);
                    $metodo = $require[1];
                    require_once $class .'.php';
                    $classe = new $class;
                    return $classe->$metodo();
                    
                }
                    
                if ( is_callable ($require) )                   
                    $require;
                
            }
            
        }
        
    }
        
?>      

home php.

<?php

 echo 'HOME';

?>

A) All files are in the same directory

B) The name of Virtual Host that I created at Apache 2.4 is routes with.

Now the problem:

When I call in the navigator https://rotas.com/ the code normally enters the class in

if ( is_callable ($require) )                   
    $require;

But it does not display the contents of the file home php. and shows no error.

However, if I do:

if ( is_callable ($require) )                   
    echo 123456;

Exit the screen correctly 123456

But the require doesn’t work at all.

Detail: When I do: https://rotas.com/contact, everything works correctly.

What will be wrong for the require_once does not work?

  • 2

    You are not invoking the callback. In this snippet if ( is_callable ($require) ) &#xA; $require;, substitia $require for $require().

  • 1

    If you want to post as an answer I accept it. It makes perfect sense, it is a call to a method, so it needs the (). Thank you very much!

1 answer

1


You’re not invoking the callback.

In the following passage:

if ( is_callable ($require) ) 
    $require;

Substitute $require for $require().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.