For example, is it possible to write code like this:
int $x = 6;
str $y = \"hello world\";
bool $z = false;
MyObject $foo = new MyObject();
Something you might try in order to simulate a poor man's strict type checking is using assert() to force the output to be of a particular type before you return it:
/**
* Get Balance
*
* @return int
*/
function getBalance()
{
/* blah blah blah */
$out = 555; //Or any numeric value
assert('is_int($out)');
return $out;
}
So you keep your assertions active all throughout development and testing, sort of like the checks the compiler does at compile-time.
Granted, the assert() page is keen to assert that you shouldn't use assertions to check input parameters, but rather use normal conditionals to check them.
This answer had what I thought was a good rule:
The rule of thumb which is applicable across most languages (all that I vaguely know) is that an assert is used to assert that a condition is always true whereas an if is appropriate if it is conceivable that it will sometimes fail.
If you're simulating strict type-checking (writing your code to viciously maintain types; not trying to validate input from the outside), then you ought to be certain what the type is unless you've made a mistake.
Update:
There's also this: http://hacklang.org/ Facebook's PHP-based language with static typing.
You could use h2tp transpiler to transpile HACK code to PHP:
You can do this thanks to Facebook Team and HACK Language.
Visit http://hacklang.org and http://hhvm.com for more info.
If you want to code directly in Hack + HHVM environment you can also use Facebook's internal IDE Nuclide
In PHP 7 are implemented "Scalar Type Declarations", e.g.:
public function getBalance(): int {
return 555;
}
You need to declare, that you will use strict types:
<?php
declare(strict_types=1);
function sum(int $a, int $b): int {
return $a + $b;
}
sum(1, 2);
?>
More information: https://wiki.php.net/rfc/scalar_type_hints_v5
No. That syntax will not work.
You could, theoretically, come up with a system of objects that enforced their own sort of strict typing, but it wouldn't perform and ...why would you want to, anyway?
If you need strict typing, use a strictly typed language.
Perhaps you should try this PHP extension https://github.com/krakjoe/strict. Support for the following types is introduced:
PHP is not strictly typed, so no. That said, it does support limited type hinting on functions - that's as close as it gets.