Jump to content

php noob question


GoDaddy

Recommended Posts

I'm currently reading php & mysql web development.

I was wondering, how do you know which kind of parameter that pass(type .. int, string, array, etc)

Let's say you have included some library that contains the following function

function foo($prices)
{
for($i=0;$i<count($prices);$i++)
{
echo $prices[$i];
}
}


How do you know that the function must take an array ?





A user could easily pass a string or an int .... isn't there a problem there?



EDIT:
Another question ... how do you know what type of variable is returned from a function call?

you might want a function to return an array of int .. but instead ... it returns a string ...??
Link to comment
Share on other sites

Yes...there could be a problem there. Unfortuanately (or fortunately) though, php is loosly typed and as so doesn't force these things.

The best thing to do is make your functions check inputted values. eg;
[code]
function foo($prices)
{
    if (!is_array($prices)) {
        exit();
    }
    for($i=0;$i<count($prices);$i++)
    {
        echo $prices[$i];
    }
}
[/code]
Of course this doesn't help a great deal because there is no error thrown. If your using php5 you can however throw exceptions. eg;
[code]
function foo($prices)
{
    if (!is_array($prices)) {
        throw new Exception("Expected array as first argument");
    }
    for($i=0;$i<count($prices);$i++)
    {
        echo $prices[$i];
    }
}
[/code]

To answer your other question. You dont. This is what makes php so simple, it can also make it quite painfull. Its not like C, there are no real data types. Thats just how it is.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.