MemoryRefresh!

Features / Type hinting   Type hinting



Questions Answers 0%

Pages   0 from 91
Questions   0 from 142

Reset


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) { // --- Look Here --- // 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); // --- Look Here --- // // Catchable fatal error: Argument 1 passed to myClass::test() // must be an instance of int, integer given stackoverflow.com
1) Type hinting is accepted only for: <?php function test(boolean $param) {} test(true); // error ?








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) { // --- Look Here --- // 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); // --- Look Here --- // // Catchable fatal error: Argument 1 passed to myClass::test() // must be an instance of int, integer given stackoverflow.com

References









Programming

Php
   
Regex
   
MySQL
   
Css
   
jQuery
   
Git
   


References