Skip to end of metadata
Go to start of metadata

TSPHP introduces cast as a new modifier for types. One can write cast on the left side of the type of Fields, Variables or Function parameters (also method parameters) to indicate that assigned values or actual parameters will be cast to the desired type. The cast modifier turns explicit casts of the corresponding variable into implicit casts every time a value is assigned to the corresponding variable (see Type juggling for more information). However, the cast modifier will not include an automatic cast if an explicit cast from the source type to the target type is missing.

TSPHP supports casts over several types (this will most probably change - see TSPHP-759 - Getting issue details... STATUS ). For instance, class A has an explicit cast to class B and class B has an explicit cast to class C. If one wants to cast the variable $a of type A to C, then one just needs to write (C)$a and not (C)(B)$a.

Please have a look at the following two examples which shows TSPHP code first and the corresponding output in PHP.

cast int $a = "a";
$a = 1;
$a = 1.0;

function void getPos(cast int $number){
	//...
}
getPos([2]);
<?php
namespace {
    mixed $a = (int) "a";
    $a = 1;
    $a = (int) 1.0;

    function void getPos(mixed $_number){
        //...
    }
    getPos((bool) [2]); //(bool) [2] results in true, 1 respectively
}
?>

 

Please be aware that one can lose data in the case where the cast modifier is used careless. See above the cast from array to int and the following example:

int $a = 1012;
cast bool $b = $a; //loss of data during the conversion - $b is now true
$a = $b; //$a is of type int but contains bool true
echo $a + 1; //output 2
  • No labels