Page 1 of 1
What is Casting a Data Type in PHP?
Posted: Thu Mar 12, 2009 11:00 am
by pankajdeoria
Hello Friends,
I am Pankaj Gupta .Can you please tell me in detail
What is Casting a Data Type in PHP
? I am a new user to this forum and PHP too.
Thank You.
Re: What is Casting a Data Type in PHP?
Posted: Thu Mar 12, 2009 2:21 pm
by pickle
Casting is using a language construct to change the type of a variable.
For example:
Code: Select all
$var = 1.223;
$var2 = (int)$var;
//$var2 now = 1
This doesn't necessarily work between all data types.
Re: What is Casting a Data Type in PHP?
Posted: Thu Mar 12, 2009 6:08 pm
by panic!
you can cast a function or method's arguments too.
Code: Select all
class cat
{
}
class dog
{
}
function cats_only(cat $xyx)
{
}
$jess=new cat();
$rover=new dog();
cats_only($jess); // works
cats_only($rover); //epic fail
Re: What is Casting a Data Type in PHP?
Posted: Thu Mar 12, 2009 6:26 pm
by Chris Corbyn
panic! wrote:you can cast a function or method's arguments too.
Code: Select all
class cat
{
}
class dog
{
}
function cats_only(cat $xyx)
{
}
$jess=new cat();
$rover=new dog();
cats_only($jess); // works
cats_only($rover); //epic fail
That's not type-casting and is misleading. It's type-hinting.
Type-casting is taking something that's one type and making it behave like it's another. The types must be compatible though.
PHP can also only type-cast between it's own primitive types, it can't type-cast say Cat to Animal and Vice-versa if you have those classes.
Re: What is Casting a Data Type in PHP?
Posted: Sat Mar 14, 2009 11:46 pm
by josh
Chris Corbyn wrote:PHP can also only type-cast between it's own primitive types, it can't type-cast say Cat to Animal and Vice-versa if you have those classes.
And just for the record you don't need to since PHP is dynamically typed ( I know you know that Chris but posting for OP )
Re: What is Casting a Data Type in PHP?
Posted: Tue Mar 17, 2009 12:38 pm
by panic!
Oh! My bad.
Re: What is Casting a Data Type in PHP?
Posted: Wed Mar 18, 2009 12:10 am
by josh
panic! wrote:Oh! My bad.
Well that wasnt towards you, I was saying about type casting not type hinting
Re: What is Casting a Data Type in PHP?
Posted: Wed Mar 18, 2009 5:51 am
by Hadi