代码之家  ›  专栏  ›  技术社区  ›  watermanio

从静态调用的函数通过$this->访问当前类。

  •  0
  • watermanio  · 技术社区  · 16 年前

    这感觉有点混乱,但我希望能够静态地调用一个成员函数,同时让类的其他部分正常工作…

    例子:

    <?php
    class Email
    {
        private $username = 'user';
        private $password = 'password';
        private $from     = 'test@example.com';
        public  $to;
    
        public function SendMsg($to, $body)
        {
            if (isset($this))
                $email &= $this;
            else
                $email = new Email();
    
            $email->to = $to;
    
            // Rest of function...
        }
    }
    
    Email::SendMsg('mqa@test.com');
    

    在本例中,如何最好地允许静态函数调用?

    谢谢!

    3 回复  |  直到 12 年前
        1
  •  1
  •   RLI123    16 年前

    因此,基本上您希望静态方法是以下对象的“快捷方式”:

    $mail = new Email();
    $mail->to = 'somebody@somewhere.com';
    $mail->body = 'this is the body';  // this property was not in your example, but assuming...
    $mail->Send();
    

    也许:

    // class declaration omitted ...    
    
    static public function SendMsg( $to, $body )
    {
        $mailobject = new self;
    
        $mailobject->to = $to;
        $mailobject->body = $body;
        $mailobject->Send();
    }
    
        2
  •  2
  •   Anthony Forloney    16 年前

    如果你想让你的方法 static 你不能有 $this 关键字 里面 方法。

    由于静态方法在没有创建对象实例的情况下是可调用的,因此伪变量$this在声明为静态的方法中不可用。

    取自 PHP: Static Keyword

        3
  •  1
  •   knittl    16 年前

    使 SendMsg 一个静态函数,创建一个名为$email的私有成员变量,并保存对新创建的email对象的引用

    推荐文章