A function (actually the constructor of another class) needs an object of class temp
as argument. So I define interface itemp
and include itemp $obj
as the function argument. This is fine, and I must pass class temp
objects to my function. But now I want to set default value to this itemp $obj
argument. How can I accomplish this?
Or is it not possible?
The test code to clarify:
interface itemp { public function get(); } class temp implements itemp { private $_var; public function __construct($var = NULL) { $this->_var = $var; } public function get() { return $this->_var ; } } $defaultTempObj = new temp('Default'); function func1(itemp $obj) { print "Got: " . $obj->get() . " as argument.\n"; } function func2(itemp $obj = $defaultTempObj) //error : unexpected T_VARIABLE { print "Got: " . $obj->get() . " as argument.\n"; } $tempObj = new temp('foo'); func1($defaultTempObj); // Got: Default as argument. func1($tempObj); // Got : foo as argument. func1(); // "error : argument 1 must implement interface itemp (should print Default)" //func2(); // Could not test as I can't define it
PHP allows you to define C++ style default argument values. In such case, if you don't pass any value to the function, it will use default argument value.
The default value of Object is Nothing (a null reference).
default parameters only work as the last arguments to the function. If you want to declare the default values in the function definition, there is no way to omit one parameter and override one following it.
PHP Parameterized functions They are declared inside the brackets, after the function name. A parameter is a value you pass to a function or strategy. It can be a few value put away in a variable, or a literal value you pass on the fly. They are moreover known as arguments.
You can't. But you can easily do that:
function func2(itemp $obj = null) if ($obj === null) { $obj = new temp('Default'); } // .... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With