why this is not possible:
$user = (User) $u[0];
but this is possible
$bool = (boolean) $res['success'];
I use PHP 7.0.
PHP type casting helps the developer to easily convert one type of value to another, or a given PHP class object can also be converted to object of a different class.
Definition and Usage Contrary to C, C++ and Java, type of PHP variable is decided by the value assigned to it, and not other way around. Further, a variable when assigned value of different type, its type too changes. This approach of PHP to deal with dynamically changing value of variable is called type juggling.
To explicitly convert a value to bool, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a bool argument. See also Type Juggling.
As I know, in PHP you can only cast to some types:
(int), (integer) - cast to integer (bool), (boolean) - cast to boolean (float), (double), (real) - cast to float (string) - cast to string (binary) - cast to binary string (PHP 6) (array) - cast to array (object) - cast to object (unset) - cast to NULL (PHP 5) (depracted in PHP 7.2) (removed in 8.0)
(see Type Casting)
Instead you could use instanceof to check of specific type:
if($yourvar instanceof YourClass) { //DO something } else { throw new Exception('Var is not of type YourClass'); }
EDIT
As mentioned by Szabolcs Páll in his answer, it is also possible to declare a return type or parameter type, but in that cases an exception (TypeError) will be throwen, if the type does not match.
function test(): string { return 'test'; } function test(string $test){ return "test" . $test; }
Since PHP 7.2 it is also possible to make the types nullable by adding ? in front of them:
function test(): ?string { return null; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With