Simple PHP routing with undefined url for php7 and lower

1.4k views Asked by At

Trying to use this php routing class on a server with php 5.4 version installed. this code works but won't be good for undefined URLs. it also has a comment line ($k[$_GET['p']] ?? $k[''])(); with the correct code behavior for php7, which makes the code work with the //404 commented block of code.

How to write the same functionality for php5.4? I guess that I want to check and replace undefined variables with $k[''] to check the URL and output the "page not found" massage but, I can't get it done correctly.

any ideas?

<?php
    class R 
    {
        private $r = [];
        function a($r, callable $c){
            $this->r[$r] = $c;
        }

        function e(){
            $k = $this->r;
            // working php7 version: ($k[$_GET['p']] ?? $k[''])();

            // trying to make the same for php5.4 here:
            $k[$_GET['p']]();       

        } 
    }

    $router = new R;

    // Home
    $router->a('/', function(){
        echo 'Home';
    });

    // About
    $router->a('/about', function(){
        echo 'About';
    });

    // 404 (works only with php7 version line of code)
    $router->a('', function(){
        echo 'Page Not Found';
    }); 

    $router->e();
?>
1

There are 1 answers

1
cn007b On BEST ANSWER

Try this:

function e() {
    $p = $_GET['p'];
    $k = isset($this->r[$p]) ? $this->r[$p] : $this->r[''];
    $k();
}

It should work.