I was testing return types with PHP 7.
I've created a simple script to test return types of PHP 7:
<?php
Class Obj {
public function __construct(){
}
public function test(): string { //a string needs to be returned
return "ok";
}
}
function foo(): Obj { //instance of Obj needs to be returned
return new Obj();
}
$o = foo();
echo $o->test(); // output: ok
Now in other programming languages when you specify a return type void
it means you cannot return anything or you will get an error. So I wrote this script:
<?php
function foo(): void {
}
foo();
Now in above script the expected output is nothing. Instead it gives me a Fatal error:
Fatal error: Return value of foo() must be an instance of void, none returned on line 2
My question is (I couldn't find it), in PHP 7 will there be a similar void
type?
null
andundefined
as special values.undefined
doesn’t mean it’s not defined. It’s the default value of a variable that’s been declared but not yet assigned, or the default return value of a function. However, you can also assign it to a variable deliberately. The real problem is that most JavaScript developers can’t tell you when you would use it as an alternative tonull
. – Endbrain