Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php function how to set default value as object?

Tags:

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 
like image 508
Sudhi Avatar asked Aug 15 '11 12:08

Sudhi


People also ask

Can you assign the default values to a function parameters in PHP?

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.

What is the default value for an object of type object?

The default value of Object is Nothing (a null reference).

Can we add two default values in function in PHP?

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.

What is $params in PHP?

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.


1 Answers

You can't. But you can easily do that:

function func2(itemp $obj = null)     if ($obj === null) {         $obj = new temp('Default');     }     // .... } 
like image 146
Arnaud Le Blanc Avatar answered Oct 18 '22 10:10

Arnaud Le Blanc