Home > database >  How do typehint a parameter of a function in php
How do typehint a parameter of a function in php

Time:12-18

I am having issue getting the return type for this function as I have mixed types in the switch. I have used mixed, it blew up. I have used string|bool and several type for union type.

* @param  $value 
* @param  string $type

public function __construct(string $type,  $value)
    {  
        $this->type    = $type;
        $this->value   = $value;
    }

I have tried everything but it didn't pass the CI/CD pipeline (AWS)

public function getValue(bool $typed = false)
    {
        if (false === $typed) {
            return $this->value;
        }

        switch ($this->type) {
            case 'boolean':
                return (bool) $this->value;
            case 'datetime':
                if (empty($this->value)) {
                    return null;
                }

                return new \DateTime($this->value);
            case 'option_tags':
                return json_decode($this->value);
            default:
                return $this->value;
        }
    }

ERROR The following are the error

  Method App\Model\Resources::getValue() has no return typehint specified.  
  Parameter #1 $time of class DateTime constructor expects string, string|true given.                                 
  Parameter #1 $json of function json_decode expects string, bool|string given.

CodePudding user response:

This ERROR is because you didn't declare the type that you want to return from getValue()

This is how you declare the return type

public function getValue(bool $typed = false): date

CodePudding user response:

You need to declare the return type to the function.

Simply to declare a return type, you need to put a : after the params, like this

public function store(Request $request): JsonResponse
  • Related