_SHEN_'s avatar

Curious about Query Builder "where"

In the api doc, the where method is declare as where($column, $operator = null, $value = null, $boolean = 'and'), but we can use it without passing the $operator. This make me wonder how can it work when we call the method, for example:

$model->where('foo', $bar);
// instead of 
$model->where('foo', value: $bar);

Normally in other language, eg Java, it make sense because we declare the same method twice as shown:

public static FooClass bar(string column, string operator, string value){}
public static FooClass bar(string column, string value){}
0 likes
5 replies
_SHEN_'s avatar

@webrobert Thanks for the reply, I had go through the method before I post this question. Let's take this $model->where('foo', $bar); as an example, the first param is not an instance of Closure, then it falls to the else block which $this->query->where(...func_get_args()); this run this code.

If I'm not wrong, translating the code will look like this:

// 1. 
$this->query->where(...func_get_args());

// 2.
$this->query->where(...['foo', $bar, null, 'and']);

// 3. 
$this->query->where('foo', $bar, null, 'and');

and here where the where being call again with my example $model->where('foo', $bar);

Please correct me any part if I understand the code wrongly.

newbie360's avatar
Level 24

@shen

User::get('id', 'name');

func_get_args() is turns the params string to array

so when we create a function

public function get($columns)
{
    $columns = is_array($columns) ? $columns : func_get_args();

    if (count($columns) == 2) {
        // return something
    }

    // keep going
}
->get('a', 'b', 'c')

or

->get(['a', 'b', 'c'])

will get the same result ['a', 'b', 'c']

passing array or string also work

1 like
_SHEN_'s avatar

@newbie360 thanks for the example given, although the count part seems like a hack, but it just makes more sense to me. Guess I just overthink some magic happened without the count array~

Please or to participate in this conversation.