user2507818
user2507818

Reputation: 3037

php: issue with pass values to parameter

option 1:

<?php 
function hookRequest($func, $params = array()){
    var_dump($func);
    var_dump($params);
}

hookRequest('func1', array('param1', 'param2'));

option 2:

<?php 
function hookRequest($func, $params){
    var_dump($func);
    var_dump($params);
}

hookRequest('func1', array('param1', 'param2'));

Question:

Both of above scripts can work. But I saw some scripts use this way: $params = array(), so just want to find out what is the difference between $params = array() and $params ?

Upvotes: 0

Views: 34

Answers (4)

Duleendra
Duleendra

Reputation: 497

Have a look on the "Function Arguments" basics in

http://php.net/manual/en/functions.arguments.php

Upvotes: 1

Francis Kim
Francis Kim

Reputation: 4285

It's called default parameters in PHP.

When you declare your function, hookRequest($func, $params = array()){... the $paramas = array() tell it to set it as an array when the passed parameter is blank.

Upvotes: 0

asifrc
asifrc

Reputation: 5841

The difference is that option 1 makes the second parameter optional, so that you can leave out the second option and the default value will be given to $param.

Option 2 makes the second parameter required, and will return a warning if you don't provide at least two parameters, e.g.

Warning: Missing argument 2 for hookRequest

Upvotes: 0

John
John

Reputation: 1085

If you don't pass anything into option1

hookRequest('func1');

then the $params is now an empty array.

function foobar($something,$foo = 'var')
{
   var_dump($something,$foo);
}

foobar('something');

Output:

string(9) "something" string(3) "var"

Upvotes: 2

Related Questions