views:

36

answers:

1

Hi I'm using Closure Compiler to compress and join a few JavaScript files the syntax is something like this;

$c = new PhpClosure();
$c->add("JavaScriptA.js")
  ->add("JavaScriptB.js")
  ->write();

How could I make it systematically add more files from an array lets say for each array element in $file = array('JavaScriptA.js','JavaScriptB.js','JavaScriptC.js',..) it would execute the following code

$c = new PhpClosure();    
$c->add("JavaScriptA.js")
  ->add("JavaScriptB.js")
  ->add("JavaScriptC.js")
  ->add
  ...
  ->write();

Thank you so much in advance!

+3  A: 

The PhpClosure code uses method chaining to reduce repeated code and make everything look slightly nicer. The functions (or at least the add function) returns $this (The object the function was called on).

The code in the first sample could be written as:

$c = new PhpClosure();
$c->add("JavaScriptA.js");
$c->add("JavaScriptB.js");
$c->write();

The middle section (The add function calls) can then be transformed so that it loops over an array of files rather than having to add a line for each file.

$files = array("JavaScriptA.js", "JavaScriptB.js");
$c = new PhpClosure();
foreach ( $files as $file ){
    $c->add($file);
}
$c->write();
Yacoby
Or, to be exactly like his code, you would say `$c = $c->add($file);`. It may not make a difference, but that depends on the class implementation.
bradlis7
@bradlis7 `add()` returns `$this`. http://code.google.com/p/php-closure/source/browse/trunk/php-closure.php
Yacoby
Well then there's no need for it. I have not messed with closure before.
bradlis7
@bradlis7 It was a very valid point though and I must admit I didn't check the source until you mentioned it :)
Yacoby
thanks for being amazing Yacoby!
Mohammad