Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value must be instance of mixed int returned AH01071

Tags:

php

In this code

<?php declare(strict_types=1);

namespace Persist;


trait IteratorTrait {
  /* #region Iterator */
  /** @var bool $valid true if a valid object */
  private bool $valid = false;
  
    public function current ( ): object { return $this; }
    public function key ( ): mixed  { return $this-> {$this->getPrimaryKey()} ; }
    public function valid ( ): bool { return $this-> valid; }
    public function next ( ): void { $this-> findNext(); }
    public function rewind ( ): void { $this-> findFirst(); }
  /* #endregion */
};

I get an error (on php 7.5) in an class that uses the trait: AH01071: Got error 'PHP message: PHP Fatal error: Uncaught TypeError: Return value of NameSpace\\test::key() must be an instance of mixed, int returned in...

If remove the :mixed on key I get an error on PHP 8.1: PHP Deprecated: Return type of NameSpace\test::key() should either be compatible with Iterator::key(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in ...

What I read here confuses me.

If I add this to the trait I get Fatal error: Attribute "ReturnTypeWillChange" cannot target property (allowed targets: method) in IteratorTrait.php on line 10

EDIT: This error occured because there was a property defined before the key() method.

Where should I change what to get this working on both 7.x and 8.x?

like image 684
theking2 Avatar asked Feb 01 '26 21:02

theking2


1 Answers

The #[\ReturnTypeWillChange] needs to appear directly before the method returning a mixed, but mixed needs to be ommitted to have this working in both PHP versions. The correct syntax is:

<?php declare(strict_types=1);

namespace Persist;


trait IteratorTrait {
  /* #region Iterator */
  /** @var bool $valid true if a valid object */
  private bool $valid = false;
  
    public function current ( ): object { return $this; }
    #[\ReturnTypeWillChange]
    public function key ( ) { return $this-> {$this->getPrimaryKey()} ; }
    public function valid ( ): bool { return $this-> valid; }
    public function next ( ): void { $this-> findNext(); }
    public function rewind ( ): void { $this-> findFirst(); }
  /* #endregion */
};

Tested on PHP 8.1.5 and 7.4.29.

like image 84
theking2 Avatar answered Feb 04 '26 11:02

theking2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!