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!

4
  • 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 Commented Feb 11, 2014 at 9:11
  • These may help you, 1. stackoverflow.com/questions/2990952/php-oop-method-chaining 2. stackoverflow.com/questions/125268/… Commented Feb 11, 2014 at 9:11
  • Using a fluent interface: sub_function() must return $this Commented Feb 11, 2014 at 9:11
  • Thanks! But i need return string... Commented Feb 11, 2014 at 9:24

2 Answers 2

5
class myclass {

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

    public function sub_function() {
        //Do your actions here
        return $this;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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)

4 Comments

Because $main is just the string MAIN, try $data->sub_function(1);
Also, this should have been an edit to your original post, not an answer
Thanks, but id need $data->main_function()->sub_function
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.