Introduction
This article explains type hinting
using PHP5. PHP5 introduces type hinting. Functions square
measure are currently able to force parameters to be objects by specifying the name
of the category within the operate prototype, interfaces, arrays or callback hint type.
However, if null values are employed because the default parameter value then it'll be
allowed as an associate argument for any later decision. If the category or interface
is nominative as a type hint then all its kids or implementations square measure are
allowed too. Type hints can't be used with scalar sorts like int or string.
Resources and Traits don't seem to be allowed either. In type hinting, a function is
able to force a parameter to be an object by the specific name of the class. If you
pass the null parameter then it will be allowed as arguments. I will
show that in the last example of allowing null values as arguments.
A Valid type class of unit category names for
arguments that receive objects and array for those who receive arrays. I will
show use of this example.
Type hint
example class
In this example I will show a simple type hint.
- <?php
- class hint
- {
- public function demo(newclass $overclass) {
- echo $overclass->var;
- }
-
- public function demo_array(array $input_array) {
- echo "<pre>"; print_r($input_array);
- }
-
- public function demo_interface(Traversable $iterator) {
- echo get_class($iterator);
- }
-
- public function demo_callable(callable $callback, $demo) {
- call_user_func($callback, $demo);
- }
- }
- class newclass {
- public $var = 'this is my hint type';
- }
- ?>
Failure to satisfy the type
hint results in a catchable error.
- <?php
- include 'demo.php';
- $hint = new hint;
- $overclass = new newclass;
-
- $hint->demo('hello');
-
- $foo = new testClass;
- $hint->demo($foo);
-
- $hint->demo(null);
-
- $hint->demo($overclass);
-
- $hint->demo_array('a string');
-
- $hint->demo_array(array('a', 'b', 'c'));
-
- $hint->demo_interface(new ArrayObject(array()));
-
- $hint->demo_callable('demo_dump', 1);
- ?>
Output
Type
hinting also works with functions as in the following
- <?php
- class hint {
- public $demo = 'this is my hint class also work with function';
- }
- function hintFunction(hint $foo) {
- echo $foo->demo;
- }
- $hint = new hint;
- hintFunction($hint);
- ?>
Output
Type
hinting allowed null value
This example will show a fatal error.
- <?php
- function demo(testClass $obj = NULL) {
- }
- demo(NULL);
- demo(new testClass);
- ?>
Output