Arguments by Reference

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sheppardzwc
Forum Newbie
Posts: 20
Joined: Mon Aug 17, 2009 3:04 pm

Arguments by Reference

Post 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?
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Arguments by Reference

Post by Jonah Bron »

It depends. Do you want bar() to give you "bar", or just do something and return $this?
sheppardzwc
Forum Newbie
Posts: 20
Joined: Mon Aug 17, 2009 3:04 pm

Re: Arguments by Reference

Post 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();
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Arguments by Reference

Post 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).
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Arguments by Reference

Post 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();
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply