0

The ability to have closures is pretty new, so I'm not sure if there is a "standard way" to do this yet but...

Is there a good way to include a function in a PHP configuration file? Right now, the project I'm working on uses JSON for the configuration files, but I can't see any way to include PHP functions in it.

I'd like to be able to do something like this (using JSON syntax)


conf file:

{
    myFunc: function($arg) {
        return $arg . ' is an argument';
    }
}

application:

json_with_func_literal_decode(...);

It doesn't have to use JSON syntax, although that'd be nice. Speed is not really a concern as long as it's reasonable. I would like to avoid the use of eval(), which is the obvious solution to this problem.

1
  • I've wrestled with this issue and IMHO closure is something that's best left out of the actual config files. In fact, I think your configuration directives should only contain primitive strings/ints/floats. It's trendy to use new language features like lambda's to accomplish simple tasks but things like your application configuration will be more portable (and readable) if you stick to the basics (e.g. string class names). When you use features that can only be implemented by a PHP config file you eliminate the ability to store your directives in YAML/XML/JSON etc. Commented Feb 19, 2012 at 17:57

1 Answer 1

3

You could simply use a PHP file without the overhead of parsing JSON/YAML for configuration like so:

<?php
return array(
    'foo' => 'bar',
    'myFunc' => function()
    {
        // ...
    }
);

And retrieve the configuration like so:

$config = include 'config.php';
Sign up to request clarification or add additional context in comments.

2 Comments

Would you explain how that return works exactly? But otherwise, that's really cool.
"Return [...] if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call" - php.net/manual/en/function.return.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.