Memory Refresh
Php



Type hinting








Programming Regex, Antipatterns, Php, Git
Type hinting is something like that you are telling your function which type should be accepted. Type casting is to "switching" between types. Type hinting isn't required, but it can allow you to catch certain types of mistakes. Type hinting is a natural process. At first it may seem like extra work but it is very helpful as your project grows in PHP. It allows for better readability and makes error control and strict programming conventions easier to apply. PHP 5 introduces type hinting (only for objects) <?php class myClass { public function test(myOtherClass $myotherclass) { echo $myotherclass->var; } } class myOtherClass { public $var = "Hello World"; } $mc = new myClass(); $moc = new myOtherClass(); $mc->test($moc); // output: Hello World $mc->test(); // Catchable fatal error: Argument 1 passed to myClass::test() // must be an instance of myOtherClass, none given Type hints can not be used with scalar types such as int or string. <?php class myClass { public function test(int $number) { echo $number; } } $mc = new myClass(); $a = (int) 10; $mc->test($a); // Catchable fatal error: Argument 1 passed to myClass::test() // must be an instance of int, integer given https://stackoverflow.com/questions/38308985/why-is-type-hinting-necessary-in-php







Programming Regex, Antipatterns, Php, Git