Bankzilla
Bankzilla

Reputation: 2096

Get Params Passed Into Function With Pre Sets

I'm looking for a way to get the values of params being set, whether it be passed it or pre-set. I tried using func_get_params(). While this does return the values being passed in, it doesn't show if values are pre-set.

public function __construct($host = 'null', $user = null, $password = null, $database = null){
var_dump(func_get_args());
die();
    $this->mysqli = new mysqli($host, $user, $password, $database);

    if ($this->mysqli->connect_errno) {
        echo("Connection failed: ". $mysqli->connect_error);
        exit();
    }
}

When no values are passed in, get an empty array output, instead of nulls. This also happens if I turn the nulls into strings.

Is there an alternative to func_get_args that also returns pre-set values?

Upvotes: 0

Views: 75

Answers (1)

Wrikken
Wrikken

Reputation: 70460

Quite verbose, you see why named parameters or more fun to work with:

<?php
class Foo {
     function __construct($host = 'null', $user = null, $password = null, $database = null){
        //getParameters 
        $ref = new ReflectionMethod(__CLASS__,__FUNCTION__);
        $args = array();
        foreach($ref->getParameters() as $param){
                $args[] = $param->getDefaultValue();
        }
        foreach(func_get_args() as $key => $arg){
           $args[$key] = $arg;
        }
        var_dump($args);
     }
}
new Foo();
/*
array(4) {
  [0]=>
  string(4) "null"
  [1]=>
  NULL
  [2]=>
  NULL
  [3]=>
  NULL
}
*/
new Foo('foo','bar');
/*
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  NULL
  [3]=>
  NULL
}
*/

Upvotes: 1

Related Questions