Ryan
Ryan

Reputation: 14649

Why and when should you typecast variables in PHP

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

Answers (2)

Francis Avila
Francis Avila

Reputation: 31621

Your "typecasting" code doesn't actually accomplish anything.

(type) $var = literal does this:

  1. Assign literal value to $var with the literal value's native type.
  2. "Return" (as an expression) the value of $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

Your Common Sense
Your Common Sense

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

Related Questions