I've come across a bit unusual scenario where my function returns multiple types string or integer. I'm trying to declare return types. Could anyone please suggest me the best practice here to declare.
I'm aware that null or other type I can use something like this
/**
* Get the result status as a formatted string
* @return string|null formatted status
*/
public function abStatus() : ?string {
but my function is like below returns string or integer
/**
* Get the score for this action
* @return string|int
*/
public function getAlphaScore() {
if ($this->type != self::TYPE_ACTION) {
return 0;
}
if (empty($this->action->status < self::STATUS_IMPORTED) {
return 'U';
}
return ActionCalculator::actionScore($this->action->score);//returns integer here
}
Now, I'm wondering how should I declare my function with return types
public function getAlphaScore() : string {
or
public function getAlphaScore() : int {
also I want to know ideas/suggestions/best practices on a situation like this where multiple return types will be returned
/**
* @param $compareAction
* @return float|int|null
*/
You don't declare the return type then.
It's either
stringorint, you can't have both.That's where PHP's weak typing kicks in.