One of the beautifull feature of programming languages came out in PHP 7 that now we also can have function return type in PHP like we have in other languages like Java, C, C# etc..
So PHP 7 adds support for return type declarations.
Now we can force a function to return a specific type of data.
In PHP 7 we have following function return types:
int : Integer data type.
1 2 3 4 5 6 |
<?php function testInt() : int{ return 5; } var_dump(testInt()); ?> |
float : Float data type.
1 2 3 4 5 6 |
<?php function testFloat() : float{ return 5.2; } var_dump(testFloat()); ?> |
array : Array data type.
1 2 3 4 5 6 |
<?php function testArray(): array { return []; } var_dump(testArray()); ?> |
bool : Boolean data type.
1 2 3 4 5 6 |
<?php function testBoolean() : bool{ return 1; } var_dump(testBoolean()); ?> |
string: String data type.
1 2 3 4 5 6 |
<?php function testString() : string{ return 'coding 4 developers'; } var_dump(testString()); ?> |
Class/Interface name : Name of the class.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php class class1{} class class2{ public function __construct() { } function get_class_1_object() :class1{ return new class1; } } $x = new class2; $y = $x->get_class_1_object(); var_dump($y); |
1 2 3 4 5 6 7 8 9 |
<?php interface A { static function make(): A; } class B implements A { static function make(): A { return new B(); } } |
self : Instance of the same class. This can only be used if function is created under any class.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php class test1{ } class test2{ function testSelf() : ? self{ return new test2(); } } $obj = new test2(); var_dump($obj->testSelf()); ?> |
callable : Valid PHP callable.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php class test{ static function testCallable(){ return 1; } } function test():callable{ $x = new test; return array($x , 'testCallable' ); return 1; } var_dump(is_callable(test())); ?> |
...