2

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?

stack
  • 10,280
  • 19
  • 65
  • 117

1 Answers1

1

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.

Community
  • 1
  • 1
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279