Jump to content

Archived

This topic is now archived and is closed to further replies.

GoDaddy

php noob question

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 ...??

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites
thanks thorpe for clearing this out ... i'm c++, java, c# developer .. so those questions came to me.

But it seems like php5 is pure OOP now, really great for me.

thanks again

Share this post


Link to post
Share on other sites

×

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.