Is it possible to explicitly declare the type of a local variable in PHP?
I know it is possible to declare the type of function parameters, function return, and class attributes. (as demonstrated below)
class HasString {
private string $value;
public function getValue() : string
{
return $value;
}
public function setAttribute(string $arg0)
{
$this->value = $arg0;
}
}
However, the following will not work.
// Tested in PHP 7.4.1
string $localVar = "value"; // Parse error: syntax error, unexpected '$localVar' (T_VARIABLE) in php shell code on line 1
Does php has a syntax that I can use to explicitly declare the type of a local variable?
This would be useful to catch bugs where a variable receives an unexpected value, and to help the IDE identify the variable type when dealing with mixed or unspecified function returns.
Solution 1:
You can using typecasting to force a variable into a type like so:
$string = (string) 3;
You'll find $string
is now the string: "3"
.
If you only want to allow one type (and not have any conversion/casting) the simple answer is: in PHP you cannot really do this as PHP is a weakly typed language. There are some workaround that you can read more about it in this question.
Solution 2:
I think to just type cast your variable is a bit risky as unexpected behaviour might occur.
If you cast an int to a string that might work in a lot of cases but could also lead to not so obvious errors.
What you are looking for are PHPDoc Annotations as there is unfortunately no way to do what you do with the class properties on the local variables. You can learn more about these here https://www.phpdoc.org/ and here https://phpstan.org/writing-php-code/phpdocs-basics
But if you are using any framework it would already come with those. Or your IDE also just supports them like for example Phpstorm or Eclipse.
Code example
public function foo(): void {
/* @var string */
$localVar;
// ... do other stuff
}