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.
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.
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
}
Last update: 421 days ago