magento2: PHP7 return types incompatibile with generate code

Preconditions

  1. PHP 7.0.8 (any compatible PHP 7 release should be sufficient though)

Steps to reproduce

  1. Blank install
  2. Create a new block and add a method with a return type in PHP7 format e.g : string
  3. Use the block in some layout somewhere
  4. Hit the frontend to use the block

Expected result

  1. The page should load and the block code be executed correctly

Actual result

Instead you get a fatal error from PHP because the generated interceptor class doesn’t have a return type at all.

PHP Fatal error:  Declaration of XX\YY\Block\CustomBlock\Interceptor::someMethod() must be compatible with XX\YY\Block\CustomBlock\::someMethod(): bool in .../var/generation/XX/YY/Block/CustomBlock/Interceptor.php on line X

This of course can be a tricky one to resolve purely based on the fact you wouldn’t want to break BC with PHP 5.X.

The only resolutions I can think of at this point is…

  1. Check the version at runtime
  2. Set the PHP version (like we set the deploy mode)

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 10
  • Comments: 27 (18 by maintainers)

Commits related to this issue

Most upvoted comments

I use Magento v2.3.2 I need to enable MAGE_PROFILER=2, but got errors like this:

Fatal error: Declaration of Magento\Framework\App\Request\PathInfo\Logger::getPathInfo(string $requestUri, string $baseUrl) must be compatible with Magento\Framework\App\Request\PathInfo::getPathInfo(string $requestUri, string $baseUrl): string in /var/www/magento/generated/code/Magento/Framework/App/Request/PathInfo/Logger.php on line 83

It looks like the same problem but with loggers generation in this time. How can I fix it?

It seems the version of zendframework/zend-code Magento 2 ships with does not support return type hints in code generation, nor is it easy to update the version of zendframework/zend-code due to conflicting dependencies.

We decided to temporarily patch this and bring in some zendframework/zend-code features to add return type hints. Here is a patch if anyone else wants this feature: https://gist.github.com/AydinHassan/064f4bbd33fc118f9fa655811df6a660.

Note that you will need to put it in your own module and rename the namespaces.

That sounds way better) Thanks for your efforts.