d-_-b
d-_-b

Reputation: 23161

php class call function within function

Could someone help me understand how I can make functions within class methods, that would allow me to do things like this:

$class->send->activation_email()

I've seen many APIs do this, so I've tried:

class MyClass 
{

    public function send()
    {

        function activation_email()
        {
            echo "success!";
        }

    }
}


Undefined property: MyClass::$send 

Upvotes: 3

Views: 122

Answers (4)

Mike
Mike

Reputation: 1988

What you are referring to (shame on no one for noticing this, for shame) is called "method chaining". A lot of big frameworks do this. Consider this example of use:

echo $obj->setName('Mike')->convertMtoN()->getName();
//  Echoes "Nike"

Cool.

But here is how it works:

class Example {

    private $name = '';

    public function setName($name) {
        $this->name = $name;

        //  We return the object, so you can call it again.
        return $this;
    }

    public function convertMtoN() {

        // Let's do Caps first
        $this->name = str_replace("M", "N", $this->name);

        // Then lowercase
        $this->name = str_replace("m", "n", $this->name);

        // We return the object, keep working
        return $this;
    }

    public function getName() {
        return $this->name;
    }
}

$name = new Example;

echo $name->setName('Mike')->convertMtoN()->getName();

Essentially, for each method that does not implicitly return a value, you simply return the object, allowing you to continue chaining.

Awesome, right?

PHP rocks (now, I know it has its faults, but with HHVM and process forking, it basically rocks [dude, you will get there]).

You can play with this here: https://ideone.com/fMcQ9u

Upvotes: -2

d-_-b
d-_-b

Reputation: 23161

Someone had answered but deleted the post. This is along the lines of what I was hoping for, and it works as expected:

class MyClass {

    public function send(){
        echo "Sending: ";
        return $this;
    }

    public function activation_email(){
        echo "activation email.";
    }
}

$myClass = new MyClass();
$myClass->send()->activation_email();

Upvotes: 0

symcbean
symcbean

Reputation: 48357

Consider:

class emailSender()
{
   function activation_email()
   {
      if (mail($this->to, $this->subj, $this->body)) {
          print $this->msg;
      }
}

class MyClass 
{
 var $send;
 function __construct()
 {
    $this->send=new emailSender();
    $this->send->msg="success!";
  }
}

$obj=new MyClass();
$obj->send->activation_email();

Upvotes: 4

Viktor Svensson
Viktor Svensson

Reputation: 755

You probably want to an instance of another class within your class. Make a variable inside your class like this:

$this->otherclass = new Otherclass();

In this case, you can call functions from your other class the following way:

$myClass->otherclass->otherClassFunction()

Upvotes: 1

Related Questions