1

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();
?>
LowMatic
  • 223
  • 2
  • 13
  • Didn't understand the question but if you wanna check `if(isset($_GET['p'])){ do something } else{ something else }` – Waqar Haider Jan 04 '17 at 06:26
  • You can use `isset()` or even `empty()` to check if it is present. – Sougata Bose Jan 04 '17 at 06:40
  • I'm trying to somehow rewrite this `($k[$_GET['p']] ?? $k[''])();` and make it work for php5.4 to get a clean "page not found" massage for undefined urls. how to use `isset()` (or, `empty()`) to check if the URL is undefined? – LowMatic Jan 04 '17 at 06:51
  • Check [this answer](http://stackoverflow.com/a/14063179/1049833) for how to call anonymous functions in PHP 5.4. – tyteen4a03 Jan 04 '17 at 06:51
  • `call_user_func($k[$_GET['p']] ?: $k[''])`? – Kris Jan 04 '17 at 07:32
  • it can work with `call_user_func($k[$_GET['p']] ?: $k[''])` but gives an undefined index error. – LowMatic Jan 04 '17 at 08:35

1 Answers1

0

Try this:

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

It should work.

cn007b
  • 16,596
  • 7
  • 59
  • 74