Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Cast to my class

Tags:

php

casting

why this is not possible:

$user = (User) $u[0]; 

but this is possible

$bool = (boolean) $res['success']; 

I use PHP 7.0.

like image 751
SexyMF Avatar asked Mar 06 '17 10:03

SexyMF


People also ask

Does PHP support type casting?

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.

What is type juggling in PHP?

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.

How do you cast a variable to a boolean?

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.


1 Answers

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; } 
like image 57
Jarlik Stepsto Avatar answered Sep 22 '22 09:09

Jarlik Stepsto