PROGRAMMING

  minte9
learningjourney




R Q

Type Hinting

Type casting is for switching between types. With type hinting you are telling your function which type should accept. It allows you to catch certain types of mistakes.
  code
class A
{
    public function test(B $b)
    {
        echo $b->var;
    }
}

class B
{
    public $var = "Hello World";
}

$a = new A();
$b = new B();

try {

    //$a->test($b); // Hello World

    $a->test("b");
        // Argument 1 passed to A::test() must be ...
        // an instance of B, string given

} catch (TypeError $e) {

    echo $e->getMessage();
}
Type hints can also be used with scalar types such as int or string.
  code
declare(strict_types=1); // Look Here

class A
{
    public function test(float $number)
    {
        return $number;
    }
}

try {

    $obj = new A();

    $no = (String) 10; // Look Here

    echo $obj->test($no);

} catch (TypeError $e) {

    echo $e->getMessage();
        // Argument 1 passed to A::test()
        // must be of the type float, string given
}

Questions    
Last update: 60 days ago
Features, SPL