简体   繁体   中英

Assign default value to route parameter in Slim

Let's say, I have

$app->get('/hello/:name', function($name){
  echo 'Hello' . $name;
});

Is it possible to have default value for $name so if I just go to

http://myurl.com/hello

*without second segment, it will out put

Hello default

If yes, How to do that ? How to assign default value to route parameter in Slim ?

I know there is Optional Route Parameter , but I'm not sure to use it since it's still experimental.

Thanks.

Try this, I've tested it. I works well.

<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/hello(/:name)', function ($name = 'default') {
    echo "Hello, $name";
});
$app->run();

You can visit like this:

http://slim.test.com/hello
http://slim.test.com/hello/srain

can not visit like this:

http://slim.test.com/hello/

update: If you want to make both of them can be visited:

<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/hello(/)(/:name)', function ($name = 'default') {
    echo "Hello, $name";
});
$app->run();

You can simply use default parameters .

$app->get('/hello/:name', function($name="default"){
  echo 'Hello' . $name;
});
$app->get('/hello/:name', function($name){
  if (empty($name)){
    $name='default';
  }
  echo 'Hello' . $name;
});

I was having a similar issue wherein I had to handle an optional parameter in the request. Try this I have tested it myself.

$app->get('/hello(/:name)',function($name="default"){
  echo 'Hello' . $name;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM