You can't typehint strings, you can only typehint objects and arrays, so this is incorrect:
function setName ( string $name = "happ") {
(The reason you don't get a compile-time error here is because PHP is interpreting "string" as the name of a class.)
The wording in the docs means that if you do this:
function foo(Foo $arg) {
Then the argument passed to foo() must be an instance of object Foo. But if you do this:
function foo(Foo $arg = null) {
Then the argument passed to foo() can either be an instance of object Foo, or null. Note also that if you do this:
function foo(array $foo = array(1, 2, 3))
Then you can't call foo(null). If you want this functionality, you can do something like this:
function foo(array $foo = null) {
if ($foo === null) {
$foo = array(1, 2, 3);
}
[Edit 1]
As of PHP 5.4, you can typehint callable
:
function foo(callable $callback) {
call_user_func($callback);
}
[Edit 2]
As of PHP 7.0, you can typehint bool
, float
, int
, and string
. This makes the code in the question valid syntax. As of PHP 7.1, you can typehint iterable
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…