简体   繁体   中英

Reference static method from code in PHP

Is there any way to reference a class static method to use with call_user_func without using strings?

Right now, the only two options I know to invoke the register method in an User class are this:

call_user_func([User::class, 'register']);
call_user_func(User::class . '::register');

Both ways require to use a string to identify the method, making code impossible to refactor.

As an example, for instance properties I'm using this workaround that works just fine:

class User {
    /**
     * @return static
    */
    public static function prop()
    {
       return new PropertyName();
    }
}

class PropertyName
{    
    public function __get($name)
    {
        return $name;
    }
}

So I could write this having autocomplete and refactoring support:

User::factory()
  ->where(User::prop()->email, $email)
  ->get_one()

To answer the question "Is there any way to reference a class static method to use with call_user_func without using strings?" - Yes

But im not sure this is what you want :D

class Foo {

    public static function bar() {
        echo "yaay \o/";
    }

}

call_user_func(function() {
    Foo::bar();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM