itsmequinn
itsmequinn

Reputation: 1084

What does a variable assignment used as an argument to a function mean in PHP?

I'm sorry, I know this is a very simple question but I've search here on SO and tried to let Google be my friend to no avail.

I'm wondering what a variable assignment as an argument to a function does in PHP. Specifically, I found this example in the Codeigniter documentation:

public function get_news($slug = FALSE)
{
    if ($slug === FALSE)
    {
        $query = $this->db->get('news');
        return $query->result_array();
    }

    $query = $this->db->get_where('news', array('slug' => $slug));
    return $query->row_array();
}

Basically, this is a method of a controller class which is supposed to take any request to the controller "News" that has an argument and query the db to see if a news item with a slug matching that argument exists.

My guess is that this initializes the variable $slug to FALSE but then if an actual "slug" argument to the method is being passed by the user, that FALSE value is immediately overwritten before the value is passed to the function, but I can't find information about this anywhere.

Thanks for your help!

Upvotes: 1

Views: 633

Answers (3)

Iznogood
Iznogood

Reputation: 12853

In this example $slug is given a default value. If you do not change it it goes in the first if() wich queries news without slugs. If you do put something as an argument it will go into the second query using the slug as a parameter.

Upvotes: 0

MintyAnt
MintyAnt

Reputation: 3058

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

A function may define C++-style default values for scalar arguments as follows:

The variable is defaulted to whatever is set in the argument if nothing was passed in, like in c++. If you give no value for the argument, it uses the default you defined. Any value you pass in for the argument overrides the default argument.

Upvotes: 3

ma cılay
ma cılay

Reputation: 739

Your assigning an default value to that parameter. If you'd call your method without a value, FALSE would be assumed as the default value for $slug.

Upvotes: 1

Related Questions