<?php
class MyClass
{
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
public function test_array(array $input_array) {
print_r($input_array);
}
}
class OtherClass {
public $var = 'Hello World';
}
?>
Failing to satisfy the type hint results in a catchable fatal error.
<?php
$myclass = new MyClass;
$otherclass = new OtherClass;
$myclass->test('hello');
$foo = new stdClass;
$myclass->test($foo);
$myclass->test(null);
$myclass->test($otherclass);
$myclass->test_array('a string');
$myclass->test_array(array('a', 'b', 'c'));
?>
Type hinting also works with functions:
<?php
class MyClass {
public $var = 'Hello World';
}
function MyFunction (MyClass $foo) {
echo $foo->var;
}
$myclass = new MyClass;
MyFunction($myclass);
?>
Type hinting allowing NULL value:
<?php
function test(stdClass $obj = NULL) {
}
test(NULL);
test(new stdClass);
?>