How can I use an expression as parameter default value?

Question

I use Laravel framework. Also I have a file named my.php which contains all my website's configurations. It looks like:

<?php

return [

    'server' => [
        'root_path' => 'Z:\\',
    ],

    /* 
     * Website Status:
     * 0 = debugging mode
     * 1 = using mode
     */
    'status' => [
        'mode' => 0,
    ],

];

Noted that my.php file is into config folder. So I can access any value of that file by using config() function like this:

echo config(my.status.mode);
//=>0

My Problem: I need to use config(my.status.mode) as a function's parameter default value. Like this:

public function ( $m = config(my.status.mode) ){
    // do stuff
}

As you know, it throws:

syntax error, unexpected '(', expecting ')'

Also my IDE throws:

Expression is not allowed as parameter default value


Now I'm looking for an approach to implement that. I can do that like this:

public function ( $m = null ){

    $m = is_null ( $m ) ? config(my.status.mode) : $m;

    // do stuff
}

But that's not clean .. is there any better alternative?


Show source
| function   | laravel   | php   2017-01-07 12:01 1 Answers

Answers ( 1 )

  1. 2017-01-07 13:01

    It's not possible, but if you're looking for more condensed solution in PHP 7 you can use new ?? operator:

    echo $m ?? config('my.status.mode');
    

    As alternative, you can create your own global Laravel helper, wrapper for config() helper which will check variable for null and will return result from config:

    $m = default('status.mode', $m);
    

    Helper can look like this:

    if (! function_exists('default')) {
        function default($config, $value)
        {
            return is_null($value) ? config('my.'.$config) : $value;
        }
    }
    

    An advantage of this method is you can add some functionality to this helper at any time. For example you could get config value translated to the current language without doing this in a controller or a model.

◀ Go back