Type Juggling

That is to say , if you assign a string value to variable var , var becomes a string . If you then assign an integer value to var , it becomes an integer .

 
$foo

 
=

 
"

 
0"

 
;

 
/

 
/

 
$foo

 
is

 
string

 
(ASCII

 
48

 
)

 
$foo

 
+=

 
2

 
;

 
/

 
/

 
$foo

 
is

 
now

 
an

 
integer

 
(2

 
)

 
$foo

 
=

 
$foo

 
+

 
1.3

 
;

 
/

 
/

 
$foo

 
is

 
now

 
a

 
float

 
(3.3

 
)

 
$foo

 
=

 
5

 
+

 
"10

 
Little

 
Piggies"

 
;

 
/

 
/

 
$foo

 
is

 
integer

 
(15

 
)

 
$foo

 
=

 
5

 
+

 
"10

 
Small

 
Pigs"

 
;

 
/

 
/

 
$foo

 
is

 
integer

 
(15

 
)





If the last two examples above seem odd , see String conversion .

הערה :

 
$a

 
=

 
1

 
;

 
/

 
/

 
$a

 
is

 
an

 
integer

 
$a[0

 
]

 
=

 
"f"

 
;

 
/

 
/

 
$a

 
becomes

 
an

 
array

 
,

 
with

 
$a[0

 
]

 
holding

 
"f

 
"





While the above example may seem like it should clearly result in $a becoming an array , the first element of which is ' f ' , consider this :

 
$a

 
=

 
"

 
1"

 
;

 
/

 
/

 
$a

 
is

 
a

 
string

 
$a[0

 
]

 
=

 
"f"

 
;

 
/

 
/

 
What

 
about

 
string

 
offsets

 
?




 
What

 
happens

 
?





Since PHP supports indexing into strings via offsets using the same syntax as array indexing , the example above leads to a problem : should $a become an array with its first element being " f" , or should "f " become the first character of the string $a ?

For this reason , as of PHP 3.0.12 and PHP 4.0b3-RC4 , the result of this automatic conversion is considered to be undefined . Fixes are , however , being discussed .

Type Casting

 
$foo

 
=

 
10

 
;

 
/

 
/

 
$foo

 
is

 
an

 
integer

 
$bar

 
=

 
(float

 
)

 
$foo

 
;

 
/

 
/

 
$bar

 
is

 
a

 
float







הערה :

 
$foo

 
=

 
(

 
int

 
)

 
$bar

 
;

 
$foo

 
=

 
(

 
int

 
)

 
$bar

 
;







When casting or forcing a conversion from array to string , the result will be the word Array . When casting or forcing a conversion from object to string , the result will be the word Object .

When casting from a scalar or a string variable to an array , the variable will become the first element of the array :

 
$var

 
=

 
'

 
ciao'

 
;

 
$arr

 
=

 
(array

 
)

 
$var

 
;

 
echo

 
$arr[0]

 
;

 
/

 
/

 
outputs

 
'ciao

 
'





When casting from a scalar or a string variable to an object , the variable will become an attribute of the object ; the attribute name will be 'scalar ' :

 
$var

 
=

 
'

 
ciao'

 
;

 
$obj

 
=

 
(object

 
)

 
$var

 
;

 
echo

 
$obj

 
-

 
scalar

 
;

 
/

 
/

 
outputs

 
'ciao

 
'