-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()

1
  • no, its different case. Commented Apr 5, 2016 at 6:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

but laravel have function like that on eloquent.
i dont understand, if i call the function only with 2 parameter, how to know second parameter is $value not $condition ?
I'm sorry for wrong link reference. Check the link in the answer again. There is logic on "how to know 2nd parameter is value not condition"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.