Jump to content


Photo

php noob question


  • Please log in to reply
2 replies to this topic

#1 GoDaddy

GoDaddy
  • New Members
  • Pip
  • Newbie
  • 7 posts

Posted 05 June 2006 - 12:47 AM

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

#2 trq

trq
  • Staff Alumni
  • Advanced Member
  • 31,041 posts

Posted 05 June 2006 - 01:01 AM

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;
function foo($prices)
{
    if (!is_array($prices)) {
        exit();
    }
    for($i=0;$i<count($prices);$i++)
    {
        echo $prices[$i];
    }
}
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;
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];
    }
}

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.

#3 GoDaddy

GoDaddy
  • New Members
  • Pip
  • Newbie
  • 7 posts

Posted 05 June 2006 - 02:28 AM

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




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users