开发者

PHP function to set the default value as an object

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 i开发者_如何学运维temp
{
    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


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

function func2(itemp $obj = null)
    if ($obj === null) {
        $obj = new temp('Default');
    }
    // ....
}


A possible problem with Arnaud Le Blanc's answer is that in some cases you might wish to allow NULL as a specified parameter, e.g. you might wish for the following to be handled differently:

func2();
func2(NULL);

If so, a better solution would be:

function func2(itemp $obj = NULL)
{

  if (0 === func_num_args())
  {
    $obj = new temp('Default');
  }

  // ...

}


PHP 8.1 and later

Since PHP 8.1 you will be able to define a new instance of an object as a default value of the function argument without error, however with some limitations.

function someFunction(Item $obj = new Item('Default'))
{
    ...
}

Documentation: PHP RFC: New in initializers


Since PHP 5.5 you can simply use the ::class to pass a class as a parameter as follow:

function func2($class = SomeObject::class) {
    $object = new $class;
}

func2(); // Will create an instantiation of SomeObject class
func2(AnotherObject::class); // Will create an instantiation of the passed class


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

function func2(itemp $obj = null)
    $obj = ValueResolver::resolve($obj, new temp('Default'));
    // ....
}

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜