Given this declaration:
(string)$my_string = 'Hello world';
*vs*
$my_string = 'Hello world';
or*
(int)$my_int = 1;
$my_int = 1;
Is there an advantage over the first way of defining a string variable in PHP?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your “typecasting” code doesn’t actually accomplish anything.
(type) $var = literaldoes this:$varwith the literal value’s native type.$varcast to the desired type.The type of
$varremains unchanged.For example:
Output is:
So there is no point to this syntax. Typecasting with a literal is almost certainly pointless.
However it can be useful to force a variable to be a certain type, for example:
$intvar = (int) $var;