Reputation: 14649
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?
Upvotes: 1
Views: 178
Reputation: 31621
Your "typecasting" code doesn't actually accomplish anything.
(type) $var = literal
does this:
$var
with the literal value's native type.$var
cast to the desired type.The type of $var
remains unchanged.
For example:
var_dump((string) $s = 1);
var_dump($s);
Output is:
string(1) "1"
int(1)
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;
Upvotes: 3
Reputation: 157839
Is there an advantage over the first way
yes. second one is more concise.
What are the advantages of typecasting variables in PHP
casting it to the expected type.
you seldom need it with strings though.
and with variable definitions you don't need it at all.
Upvotes: 1