Type hinting are type declarations to function arguments, return values and class properties. PHP ensures the value is of the same type you declared or throws an TypeError. It isn't required but very useful to catch mistakes and helpful to others reading your code to understand what is up.
Function arguments
To type hint our function argument message of our method error, we would add string just in front of our argument:
<?php
class Logger
{
private $message;
function alert(string $message)
{
return $this->message;
}
}
$logger = new Logger;
$logger->alert('Wrong password');
This makes sure that whatever is passed to our method, $message
is always a type of string or an error is thrown.
Return values
This also works for our response. In this case we expect our method would return a string and so we add : string
after our argument:
<?php
class Logger
{
private $message;
function alert($message): string
{
return $this->message;
}
}
$logger = new Logger;
$logger->alert('Wrong password');
Whatever we would pass to our error method as arguments (string, integer, boolean, array etc.), our return should always be a type of string otherwise an error is thrown.
Class properties
Besides methods we could also type hint our properties. In case of our message we add the annotation @var string
:
class Logger
{
/**
* @var string
*/
private $message;
function alert($message)
{
return $this->message;
}
}
$logger = new Logger;
$logger->alert('Wrong password');
This makes sure that whenever we call this property it should be a type of string or an error is thrown.
All type hints together
If we would save logging messages in our database and we would like to create getters and setters for our message, we could use all 3 types of type hinting as followed:
class Logger
{
/**
* @var string
*/
private $message;
function setMessage(string $message): void
{
$this->message = $message;
}
function getMessage(): string
{
return $this->message;
}
}
I have type hinted the property $message
, the argument as string and added the expected result of a string for the getMessage()
method. For the setMessage
method I added the expected result void
. This means we do not expect anything for this method, this is because the setter would only set our property and doesn't return us anything.
Type hinting methods
Some would also type hint their methods, similar to our property, but this isn't necessary because we already type hinted our property, argument and response.
Let me know what you think and share your knowledge on Type Hinting!
Top comments (1)
Yloved type PHP!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.