LaneWalker
LaneWalker

Reputation: 255

How to use a function with a set variable in PHP?

I have this function in a separate .php file:

function getBasicHerpInfo($offset='0'){
    # Get the details of two herps from the database, offset by $offset
    $sql = "SELECT NUM, COLOR, COST
            FROM HERPES
            ORDER BY NUM
            LIMIT $offset,2";
    return DBIface::connect()->query($sql);
}

So what it apparently does it get the details of two herps. I want to display the details of two herps on each page, and the details that are displayed changes because of a variable called $offset, rather than making a new page for each pair of herps. This is also useful when I want to add more herps to the database without making a new page, it should just work.

So my problem is, I'm not sure how to properly pass the variable $offset into the function, because it seems it is already set? Is it a default, or do I have to pass it into the function in some special way?

Upvotes: 0

Views: 36

Answers (2)

Mark Miller
Mark Miller

Reputation: 7447

The declaration:

function getBasicHerpInfo($offset='0') { ... }

is setting a default value to $offset of 0. This means, if you call

getBasicHerpInfo();

then $offset will be set to 0. You can override the default by calling

getBasicHerpInfo(5); // or other number

which will give $offset a value of 5. In short, you only need to pass a parameter to the function if you want $offset to have a value other the default setting of 0.

Upvotes: 1

SMAK
SMAK

Reputation: 51

Yes, you are right. If function call fails to pass any value to the fucntion, then the assignment is used a "default value" for the variable, but please try changing:

function getBasicHerpInfo($offset='0') { ... }

To

function getBasicHerpInfo($offset=0) { ... }

Upvotes: 0

Related Questions