tags:

views:

45

answers:

3

This feels a bit messy, but I'd like to be able to call a member function statically, yet have the rest of the class behave normally...

Example:

<?php
class Email
{
    private $username = 'user';
    private $password = 'password';
    private $from     = '[email protected]';
    public  $to;

    public function SendMsg($to, $body)
    {
        if (isset($this))
            $email &= $this;
        else
            $email = new Email();

        $email->to = $to;

        // Rest of function...
    }
}

Email::SendMsg('[email protected]');

How best do I allow the static function call in this example?

Thanks!

+2  A: 

If you want your method to be static you cannot have $this keyword inside the method.

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

Taken from PHP: Static Keyword

Anthony Forloney
Interestingly, it is available but is actually a reference to the calling object. Scary, huh?
webbiedave
That is interesting, I would have loved to have tested it out if I had a PHP IDE at work but I cannot. :(
Anthony Forloney
I know you cant access $this in the static method, but I want to be able to also call the method from other methods within the class in other circumstances...
MQA
@MQA: That is not something I have much expertise with, have you tried knittl's proposed solution?
Anthony Forloney
+1  A: 

make the SendMsg a static function, create a private member variable called $email and save a reference to a newly created Email object

knittl
+1  A: 

So basically you want the static method to be a "shortcut" for:

$mail = new Email();
$mail->to = '[email protected]';
$mail->body = 'this is the body';  // this property was not in your example, but assuming...
$mail->Send();

Perhaps:

// class declaration omitted ...    

static public function SendMsg( $to, $body )
{
    $mailobject = new self;

    $mailobject->to = $to;
    $mailobject->body = $body;
    $mailobject->Send();
}
RobNY
Exactly that! Don't know why I hadn't thought of using new self. Thanks.
MQA