- Php
- Features
- Autoload
- Class Reflection
- Magic Methods
- Exceptions
- Late Static Binding
- Type Hinting ♣
- Spl
- Phpunit
- Phar
- Composer
- Guzzle
- Carbon
- Faker
- Math
- Requests
- Design Patterns
- Singleton Pattern
- Observer Pattern
- Strategy Pattern
- Registry
- Symfony
- Routes
- Annotations
- Flex
- Controllers
- Doctrine
- Templating
- Versions
- Php7.4
- Php8.0
- Modern Php
- Composer
- Slim Framework
- Autoloader
- Package
- Releases
- Generators
- Dependency Injection
- Middleware
- Framework
- App
- Http Foundation
- Front Controller
- Routing
- Render Controller
- Resolver
- Soc
- Frameworks
- Symfony V5
- Laravel V8
- Laminas V3
- Codeigniter V4
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
}