Jump to content

Undefined variable when routing


RaiN3772

Recommended Posts

Hello there, basically i have a problem accessing a variables

so my files structure is

 

- Project Root
    - app
    - inc
    - .htaccess
    - index.php


index.php code is basically 

require_once __DIR__ . '/inc/core.php';

the core file inside inc folder is

$test = 1;

require_once 'inc/classes/router.php';
$route = new Route();
include 'routes.php';

the router class inside inc/classes/router.php is

class Route {

    private function simpleRoute($file, $route){

        if(!empty($_REQUEST['uri'])){
            $route = preg_replace("/(^\/)|(\/$)/","",$route);
            $reqUri =  preg_replace("/(^\/)|(\/$)/","",$_REQUEST['uri']);
        }else{
            $reqUri = "/";
        }

        if($reqUri == $route){
            $params = [];
            include($file);
            exit();

        }

    }

    function add($route,$file){

        //will store all the parameters value in this array
        $params = [];

        //will store all the parameters names in this array
        $paramKey = [];

        //finding if there is any {?} parameter in $route
        preg_match_all("/(?<={).+?(?=})/", $route, $paramMatches);

        //if the route does not contain any param call simpleRoute();
        if(empty($paramMatches[0])){
            $this->simpleRoute($file,$route);
            return;
        }

        //setting parameters names
        foreach($paramMatches[0] as $key){
            $paramKey[] = $key;
        }

        //replacing first and last slashes
        //$_REQUEST['uri'] will be empty if req uri is /
        if(!empty($_REQUEST['uri'])){
            $route = preg_replace("/(^\/)|(\/$)/","",$route);
            $reqUri =  preg_replace("/(^\/)|(\/$)/","",$_REQUEST['uri']);
        }else{
            $reqUri = "/";
        }

        //exploding route address
        $uri = explode("/", $route);

        //will store index number where {?} parameter is required in the $route 
        $indexNum = []; 

        //storing index number, where {?} parameter is required with the help of regex
        foreach($uri as $index => $param){
            if(preg_match("/{.*}/", $param)){
                $indexNum[] = $index;
            }
        }

        //exploding request uri string to array to get
        //the exact index number value of parameter from $_REQUEST['uri']
        $reqUri = explode("/", $reqUri);

        //running for each loop to set the exact index number with reg expression
        //this will help in matching route
        foreach($indexNum as $key => $index){
        
             //in case if req uri with param index is empty then return
            //because url is not valid for this route
            if(empty($reqUri[$index])){
                return;
            }
            
            //setting params with params names
            $params[$paramKey[$key]] = $reqUri[$index];


            //this is to create a regex for comparing route address
            $reqUri[$index] = "{.*}";
        }

        //converting array to sting
        $reqUri = implode("/",$reqUri);

        //replace all / with \/ for reg expression
        //regex to match route is ready !
        $reqUri = str_replace("/", '\\/', $reqUri);

        //now matching route with regex
        if(preg_match("/$reqUri/", $route))
        {
            include($file);
            exit();

        }
    }

    function notFound($file){
        include($file);
        exit();
    }
}

and the routes.php file inside the inc folder is

$route->add("/", "app/index.php");
$route->add("/home","app/home.php");
$route->notFound("app/404.php");

and the index.php file inside the app folder is simple

echo $test;

but all i get is 

Undefined variable $test

so literally i tried everything i know of for 2 days to get around this but i absolutely have no idea, i even tried to draw the file structure to see if they all are in the same page (i think so) but no idea.

 

can someone point me to what is going on and why? thanks in advanced 

Link to comment
Share on other sites

You're including your app/index.php file inside your Route::add function.  As such, it's variable scope is the same as that function.  $test does not exist within that scope (it's in the global scope) so you're getting an undefined variable error.

I would suggest creating another class which handles including your content file as well as setting up any variables you want to be defined within it's scope.

 

Link to comment
Share on other sites

2 hours ago, kicken said:

You're including your app/index.php file inside your Route::add function.  As such, it's variable scope is the same as that function.  $test does not exist within that scope (it's in the global scope) so you're getting an undefined variable error.

I would suggest creating another class which handles including your content file as well as setting up any variables you want to be defined within it's scope.

 

im not even sure how to do that, i got this router from github as im still learning/experimenting, can you give me a code or something to make it work?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.