1

I have to learn about OOP chaining:

$data = new myclass;
$data->sub_function()->main_function();

But now I want to code it looks like this:

$data = new myclass;
$main = $data->main_function();
$sub = $main->sub_function();

If so how would write the class functions for this?

Please help me!

UserNaN
  • 137
  • 2
  • 13
  • The other way around... so: $data = new myclass; $sub = $data->sub_function(); $main = $sub->main_function(); Since this is exactly equal to your first post, only you're using a temporary variable instead of directly chaining it – Tularis Feb 11 '14 at 09:11
  • These may help you, 1. http://stackoverflow.com/questions/2990952/php-oop-method-chaining 2. http://stackoverflow.com/questions/125268/chaining-static-methods-in-php – Vijayakumar Selvaraj Feb 11 '14 at 09:11
  • Using a `fluent interface`: sub_function() must return `$this` – Mark Baker Feb 11 '14 at 09:11
  • Thanks! But i need return string... – UserNaN Feb 11 '14 at 09:24

2 Answers2

5
class myclass {

    public function main_function() {
        //Do your actions here
        return $this;
    }

    public function sub_function() {
        //Do your actions here
        return $this;
    }
}
TMH
  • 6,096
  • 7
  • 51
  • 88
0
class myclass {
    public function main_function() {
        return 'MAIN ';
    }
    public function sub_function($str) {
        if ($str == 1) $result = 'SELECT 1';
        else if ($str == 2) $result = 'SELECT 2';
        else $result = 'NOT FOUND';
        return $result;
    }
}
$data = new myclass;
$main = $data->main_function();
$sub = $main->sub_function(1);
echo $sub; // Fatal error: Call to a member function sub_function() on a non-object...

I need return string in each functions (not set value/key)

UserNaN
  • 137
  • 2
  • 13
  • Because `$main` is just the string `MAIN`, try `$data->sub_function(1);` – TMH Feb 11 '14 at 14:58
  • Also, this should have been an edit to your original post, not an answer – TMH Feb 11 '14 at 15:13
  • Thanks, but id need `$data->main_function()->sub_function` – UserNaN Feb 11 '14 at 19:31
  • The only way you could do that is if `main_function()` returned `$this`, otherwise you're trying to run `sub_function` on a string, not your class. If you show us more of what you're trying to do we might be able to help more. – TMH Feb 11 '14 at 21:31