PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 23, 2022

[FIXED] How do typehint a parameter of a function in php

 November 23, 2022     php, phpstan, symfony     No comments   

Issue

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.

Solution

In modern PHP you can either provide a list of all possible types:

// Tweak type list your exact needs
public function getValue(bool $typed = false): bool|DateTime|null

... or use mixed if the method can indeed return anything:

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

In older versions, you can only use the @return tag in the docblock:

/**
 * @param bool $typed
 * @return mixed
 * @throws Exception
 */

I understand PHPStan will be happy with all options.



Answered By - Álvaro González
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing