Search code examples
phpcasting

PHP Cast to my class


why this is not possible:

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

but this is possible

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

I use PHP 7.0.


Solution

  • 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  (real deprecated in PHP 8.0)
    (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;
    }