Is it possible to declare a method static and nonstatic in PHP?

后端 未结 5 1478
北荒
北荒 2020-12-01 09:04

Can I declare a method in an object as both a static and non-static method with the same name that calls the static method?

I want to create a class that has a stati

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 09:37

    Sorry for bumping an old thread, but I would like to expand on @lonesomeday 's answer. (Thanks @lonesomeday for the initial code sample.)

    I was also experimenting with this as well, but did not want to call the methods as he called them in the original post. Instead I have the following, which seems to work:

        class Emailer {
    
        private $recipient;
    
        public function to( $recipient )
        {
            $this->recipient = $recipient;
            return $this;
        }
    
        public function sendNonStatic()
        {
            self::mailer( $this->recipient );
        }
    
        public static function sendStatic( $recipient )
        {
            self::mailer( $recipient );
        }
    
        public function __call( $name, $arguments )
        {
            if ( $name === 'send' ) {
                call_user_func( array( $this, 'sendNonStatic' ) );
            }
        }
    
        public static function mailer( $recipient )
        {
            // send()
            echo $recipient . '
    '; } public static function __callStatic( $name, $arguments ) { if ( $name === 'send' ) { call_user_func( array( 'Emailer', 'sendStatic' ), $arguments[0] ); } } } Emailer::send( 'foo@foo.foo' ); $Emailer = new Emailer; $Emailer->to( 'bar@bar.bar' ); $Emailer->send();

提交回复
热议问题