At the time of this writing PHP next would be PHP 5.7. Ultimately this would need to go to the PHP request for contribution. But before wasting time there with something poorly thought out. I’d rather hash things out some.
Strict Variables.
Strict Variables would be a class of PHP variables that will not allow themselves to have their datatype changed once declared. They must also be explicitly declared with the strict keyword. If you try to create them without the keyword then the engine assumes you meant scalar for legacy reasons. The declaration looks like this.
// in procedural code
strict integer $a = 5;
// in a class
class MyClass {
public strict integer $a = 2
}
If a strict variable is compared to a scalar with a different datatype using the loose comparison operator, the scalar must recast.
strict integer $a = 5;
$b = '5';
echo $a == $b ? 'true' : 'false'; // will echo 'true'
If two strict variables are compared recasting won’t be allowed, so the loose comparison operator will be forced to behave like a strict comparison operator.
strict integer $a = 5;
strict string $b = '5';
echo $a == $b ? 'true' : 'false'; // will echo 'false'
If a strict variable is assigned to a value of a different type, that value will be recast and a E_USER_WARNING will be raised.
strict integer $a = 5;
$a = '2'; // raises warning.
The warning can be avoided with a new “cast and assign” operator, similar in concept to the existing error suppression operator and using the same @ symbol which is otherwise unused in PHP.
strict integer $a = 5;
$a @= '3'; // cast '3' to the datatype of the strict variable $a before assigning to $a.
Finally, as a shorthand the programmer can assign datatype and value together by using the strict keyword alone.
strict $a = 5; // $a will be an integer since it's being assigned an integer value.
Strict variables hold their datatype until unset. They would provide a system for experienced programmers to explicitly manage and control datatypes without interfering with the ability of novice programmers to ignore the concept of datatype until they are ready to tackle it.
Thoughts?