4

I would like to keep options in a Config class, so I don't need to change several (identical) values when changing (e.g.) MySQL database. So far I'm accessing these options like:

Config::$credentials["mysql"]["username"]

now, I would like to set a "dynamic" default value for a function, but PHP won't let me do something like

public function get_single_db_entry($uid, $table=Config::$credentials["mysql"]["table"]) {
    // logic here...
}

What I would like to know: Is there any chance to keep default parameters' values dynamic?

4
  • why not use constants for this? Commented Apr 26, 2012 at 13:28
  • @llamerr I like the array look ;) (but constants wouldn't work here as well, would they?) Commented Apr 29, 2012 at 14:13
  • 1
    constants works fine, why not? codepad.org/EkLf19Lh Commented May 7, 2012 at 9:13
  • 1
    i also tested this as class constant but you can't have class constant as array, so you need something else, like in answer for example codepad.org/GfFvhiOa Commented May 7, 2012 at 9:25

2 Answers 2

3

I think it is not possible this way. But you can render a static default value to it, and in the first line, if the value is unchanged by the caller, you just assign, the dynamic value.

public function get_single_db_entry($uid, $table=0) {
    if $table == 0 
      $table = Config::$credentials["mysql"]["table"]
    // logic here...
}

A bit workaround, but it should work.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use my tiny library ValueResolver in this case, for example:

$table = ValueResolver::resolve($table, Config::$credentials["mysql"]["table"]);

and don't forget to use namespace use LapaLabs\ValueResolver\Resolver\ValueResolver;

There are also ability to typecasting, for example if your variable's value should be integer, so use this:

$id = ValueResolver::toInteger('6 apples', 1); // returns 6
$id = ValueResolver::toInteger('There are no apples', 1); // returns 1 (used default value)

Check the docs for more examples

Comments

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.