Johnson Jason
Johnson Jason

Reputation: 721

Wouldn't the if statement in this PHP function be useless?

I am trying to work on someones code and ran into this.

private function getAttImages($limit, $forumIds = 0, $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null)
    {
        $fids = '';

        if ($forumIds)
        {
            $r = '';
            if ($fidsReverse)
            {
                $r = ' NOT ';
            }

            if (is_array($forumIds))
            {
                $forumIds = implode(',', $forumIds);
            }

            $fids = ' AND forums_topics.forum_id ' . $r . ' IN (' . $forumIds .  ')';
        }

function continues to other things. However, the question is that first if statement if($forumIds) wouldn't it be useless if every time this function is called $forumIds is set to 0 ?

Upvotes: 0

Views: 163

Answers (3)

Matt
Matt

Reputation: 2869

This is the default value for this function if nothing else is specified. It means that if nothing is entered when calling the function, it will default be 0 and the function will essentially do nothing.

Examples:

getAttImages(5, 1) Will essentially set $limit to 1 and $forumids to 1. The rest of the parameters will be set to their default values as nothing is entered ( $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null )

The only required parameter is limit as it has no default value in it. So, at minimum the function can be called like so:

getAttImages(0); and the rest will just default to the values defined in the function. However, this code won't do anything as $forumIds will be 0.

Upvotes: 1

tgreen8091
tgreen8091

Reputation: 11

The code

..., $forumIds = 0, ...

is setting up the default for that variable. It can be overridden with any value when called, but will default to 0 if no value for $forumIds is provided.

See the PHP documentation: http://php.net/manual/en/functions.arguments.php#functions.arguments.default.

Upvotes: 1

GRY
GRY

Reputation: 724

No. $forumIds is set to zero in the function parameters, but that zero is only applied to $forumIds if someone calls the function but does not explicitly set a value for that parameter.

Upvotes: 1

Related Questions