skip to Main Content

I’m trying to do something similar to the segment structure in the Codeigniter system.

I want to transfer the parameters I get via REQUEST_URI to a function and call them with a variable name I want inside the function.

Example: /news/stock


$arguments = explode('/',$_SERVER['REQUEST_URI']);

// I want to pass this array to a function called route.

//But I want to call it like this.

call_user_func('route', $arguments); 

// Here the arguments go as arrays but below is what I want.

function route($page,$slug)
{
  //...
}



Parameters can be more than one. I want to specify the names in the function arguments in the function itself, in order of parameters.

Would you help me with this topic ?

2

Answers


  1. I assume you’re looking for spread operator.
    Or in PHP known as arguments unpacking.
    https://www.php.net/manual/en/functions.arguments.php

    Try this:

    route(...$arguments);
    

    I update your code to understand better.

    $arguments = explode('/',$_SERVER['REQUEST_URI']);
    
    route(...$arguments); 
    
    // Here the arguments going as you want!!!
    
    function route($page,$slug)
    {
      echo $page;// news
      echo $slig;//stock
    }
    
    Login or Signup to reply.
  2. Try this:

    $arguments = explode('/',$_SERVER['REQUEST_URI']);
    function route ($arguments) {
    if (isset($arguments[1]) && $arguments[1] == 'news' && isset($arguments[2])) {
     $page = isset($arguments[1]);
     $slug = isset($arguments[2]);
     echo $page . ' - ' . $slug;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search