Page 1 of 1

Arguments by Reference

Posted: Mon Nov 01, 2010 10:17 pm
by sheppardzwc
Hi guys,

Stumbled upon something earlier and wanted to ask. Can you pass arguments from a return function to another function in OOP? (PHP)

For example:

Code: Select all

class foo {
    function bar() {
        return 'bar';
    }
    
    function printBar($sometypeofargumentfrombar()) {
         print($sometypeofargument);
    }
}
$foo = new foo();
$foo->bar()->printBar();

Is there any way to make this work?

Re: Arguments by Reference

Posted: Mon Nov 01, 2010 10:29 pm
by Jonah Bron
It depends. Do you want bar() to give you "bar", or just do something and return $this?

Re: Arguments by Reference

Posted: Mon Nov 01, 2010 10:31 pm
by sheppardzwc
Jonah Bron wrote:It depends. Do you want bar() to give you "bar", or just do something and return $this?
Probably return bar. It'll be fetching a template, and then outputting it, so:

$template->fetch('header')->output();

Re: Arguments by Reference

Posted: Tue Nov 02, 2010 11:44 am
by Jonah Bron
Well, is the template an object with an output() method?

Actually, to answer your question: no. You can only return one thing. Basically either a string, an integer, an array, another object, or $this (providing it's a class method).

Re: Arguments by Reference

Posted: Tue Nov 02, 2010 1:32 pm
by AbraCadaver
It's called method chaining and Jonah is right, you need to return an object, normally $this. Just an example:

Code: Select all

class Template {
   public $content;

   public function fetch($template) {
      $this->content = file_get_contents("$template.tpl");
      return $this;
   }

   public function output() {
      if(isset($this->content)) {
         print($this->content);
      }
      return $this;  //maybe needed to continue a chain
   }
}

$template = new Template;
$template->fetch('header')->output();