Skip to content

unwanted errors magical methods in trait #19121

@rino1

Description

@rino1

PREMISE

To simplify things, only the __invoke() method will be considered.

Here's my scenario

+ tree
├── MyTrait.php
├── use.php
└── use-as-public.php



+ cat MyTrait.php
<?php
trait MyTrait {
    private function __invoke(){}
    
    //protected function __invoke(){} // present the same problems

    /*
     * other magical methods
     * (as __toString(), __clone(), __debugInfo(), etc.)
     * present the same problems
     */
}



+ cat use.php
<?php require "MyTrait.php";
new class {
    use MyTrait;
};



+ cat use-as-public.php
<?php require "MyTrait.php";
new class {
    use MyTrait {
        __invoke as public;
    }
};

Let's do some tests

CASE 1

+ php MyTrait.php
PHP Warning:  The magic method MyTrait::__invoke() must have public visibility in MyTrait.php on line 3

But we're in a trait, and in my opinion, certain things should be evaluated differently than a class.
The error we saw shouldn't appear!!!
I would limit the checking to syntax errors only: I would only do the more refined checks within a class.

CASE 2

+ php use.php
PHP Warning:  The magic method MyTrait::__invoke() must have public visibility in MyTrait.php on line 3

If anything (in accordance with what was said above)

PHP Warning: The magic method class@anonymous::__invoke() must have public visibility in use.php on line 3

CASE 3

+ php use-as-public.php
PHP Warning:  The magic method MyTrait::__invoke() must have public visibility in MyTrait.php on line 3

If anything (in accordance with what was said above)

PHP Warning: The magic method class@anonymous::__invoke() must have public visibility in use-as-public.php on line 3

but, in reality, I also consider the error just seen to be unwanted, in fact the appropriate adaptation has been made

+ grep 'as public' use-as-public.php
        __invoke as public;

and is no need to add anything else: the code speaks for itself.

CONCLUSION

In a future version of PHP, I think certain aspects should be revised.
What do you think?

Would anyone be willing to create a dedicated official RFC?
https://wiki.php.net/rfc/howto

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions