Take the following function for example:
private function connect($method, $target = $this->_config->db()) {
try {
if (!($this->_pointer = @fopen($target, $method)))
throw new Exception("Unable to connect to database");
} catch (Exception $e) {
echo $e->getMessage();
}
}
As you can see I inserted the function $this->_config->db()
into the parameter $target
as it's default value. I understand this is not the correct syntax and am just trying to explain my aim.
$this->_config->db()
is a getter function.
Now I know I can use an anonymous function and call it via $target
later, but I want $target
to also accept direct string values.
How could I give it a default value of the whatever is returned by $this->_config->db()
and still be able to overwrite it with a string value?
You can use
is_callable()
andis_string()
.Why not accept NULL values by default (test with
is_null()
) and if so call your default function?I would perform a check to see if a value was passed and call my function in a simple check inside the method: