-1

I want make function with 3 parameter, first parameter is $field, second parameter is $condition and last parameter is $value. the function what I make like this:

function where($field, $condition = ' = ', $value);

i want call the function run with this code :

->where('name', 'andi')

and condition will be the default ( = ).

it's easy if $condition in last parameter, but i want $condition in middle.

if i call the function only with 2 parameter, how to know second parameter is $value not $condition ? any idea ?

thank you in advance.

SOLVED with func_num_args()

randawahyup
  • 389
  • 2
  • 5
  • 15

1 Answers1

2

No this is not possible. You cannot have default arguments hanging in the middle of the arguments. Check the doc: http://php.net/manual/en/functions.arguments.php

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

If you insist on putting it in the middle, make your $value to be null as default too, such that it become like this:

function where($field, $condition = ' = ', $value = null);

Similar to how laravel did it: https://github.com/illuminate/database/blob/91622fc886baf6263de9f93237929dcc5d61537c/Query/Builder.php#L480

In order to know whether you are dealing with where($field, $conditions, $value) ,or where($field, $value), you do a simple argument counts using func_num_args(), to know that which calls are you dealing with.

Lionel Chan
  • 7,894
  • 5
  • 40
  • 69