<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PHP in Action &#187; Hello world program</title>
	<atom:link href="http://blog.agilephp.com/tag/hello-world-program/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.agilephp.com</link>
	<description>Dagfinn Reiersøl on PHP, agile development, Ruby and other addictive substances</description>
	<lastBuildDate>Mon, 28 Sep 2009 14:35:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Real programming with PHP 5.3 (part 2): JavaScript-style classes</title>
		<link>http://blog.agilephp.com/2009/03/31/real-programming-with-php-53-part-2-javascript-style-classes/</link>
		<comments>http://blog.agilephp.com/2009/03/31/real-programming-with-php-53-part-2-javascript-style-classes/#comments</comments>
		<pubDate>Tue, 31 Mar 2009 11:45:10 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[PHP 5.3]]></category>
		<category><![CDATA[Hello world program]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://blog.agilephp.com/?p=1535</guid>
		<description><![CDATA[
In part one of this series, we looked at the ability to use lambda functions or closures to process arrays. In this part, we will see how closures can be used to build classes in a completely new way.


After I did my own research, I discovered that someone had beat me to it. As early [...]]]></description>
			<content:encoded><![CDATA[<p>
In <a href="http://blog.agilephp.com/2009/03/19/real-programming-with-php-53-part-1-array-processing/">part one of this series</a>, we looked at the ability to use lambda functions or closures to process arrays. In this part, we will see how closures can be used to build classes in a completely new way.
</p>
<p>
After I did my own research, I discovered that someone had beat me to it. As early as September last year Fredrik Holmström wrote about <a href="http://loveandtheft.org/2008/09/20/javascript-oo-python-ducktyping-in-php53/">Javascript-OO &#038; Python-DuckTyping in PHP5.3</a>.
</p>
<p>
I&#8217;ve done the same thing independently and somewhat differently, so it&#8217;s interesting to compare. Unlike Holmström, I&#8217;m defining the closures inside the constructor for the class that&#8217;s using them. That makes the code that uses the class a little more similar to what we&#8217;re used to.
</p>
<p>
Let&#8217;s start with a &#8220;Hello world&#8221; example.
</p>
<pre class="brush: php">
class HelloWorldWithClosures {
    private $hello;
    private $goodbye;

    public function __construct() {
        // If we try using $this inside the closure, we get a syntax error.
        // So we need another variable name, which is basically arbitrary.
        $self = $this;

        // $self is not actually used inside this method/closure, but we want to be consistent.
        $this-&gt;hello = function() use ($self) {
            echo &quot;hello world...\n&quot;;
        };

        $this-&gt;goodbye = function() use ($self) {
            $self-&gt;hello();
            echo &quot;...and goodbye for now\n&quot;;
        };
    }

    public function __call($method,$args) {
        return call_user_func_array($this-&gt;$method,$args);
    }
}
</pre>
<p>
The closures are instance variables in the class, and the __call() method is set up to call the correct closure when calling the method in the usual way in PHP.
</p>
<p>
Now we can call a plain method that uses nothing else from the class:
</p>
<pre class="brush: php">
$obj = new HelloWorldWithClosures;
$obj-&gt;hello(); // prints &quot;hello world...&quot;
</pre>
<p>And we can call the goodbye() method that starts by calling hello():</p>
<pre class="brush: php">
$obj = new HelloWorldWithClosures;
$obj-&gt;goodbye();
// prints &quot;hello world...
//...and goodbye for now&quot;
</pre>
<p>We can also add new methods to object that&#8217;s already instantiated without changing the class:</p>
<pre class="brush: php">
$obj-&gt;helloAgain = function() use($obj) {
    $obj-&gt;goodbye();
    echo &quot;...and hello again\n&quot;;
};
</pre>
<p>
This last example exploits the somewhat vulgar fact that you can still add public instance variables on the fly to an object, as in PHP 4.
</p>
<p>
A different approach that avoids this, but is a bit more verbose, would be to use an array to store the closures in the object:
</p>
<pre class="brush: php">
class HelloWorldWithClosures2 {
    public $methods = array();

    public function __construct() {
        $self = $this;

        $this-&gt;methods[&#039;hello&#039;] = function() use ($self) {
            echo &quot;hello world...\n&quot;;
        };

        $this-&gt;methods[&#039;goodbye&#039;] = function() use ($self) {
            $self-&gt;hello();
            echo &quot;...and goodbye for now\n&quot;;
        };
    }

    public function __call($method,$args) {
        return call_user_func_array($this-&gt;methods[$method],$args);
    }
}
</pre>
<p>
In addition, we would normally need to throw an execption when a method does not exist. The blog post I linked to at the beginning has this feature.
</p>
<p>
Those are the basics of how to write JavaScript-classes in PHP 5.3. Whether you actually want do it this way depends on your needs.  There&#8217;s no point unless you actually want to use the flexibility this style of programmer affords.</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=PHP%20in%20Action&amp;siteurl=http%3A%2F%2Fblog.agilephp.com%2F&amp;linkname=Real%20programming%20with%20PHP%205.3%20%28part%202%29%3A%20JavaScript-style%20classes&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F03%2F31%2Freal-programming-with-php-53-part-2-javascript-style-classes%2F"><img src="http://blog.agilephp.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://blog.agilephp.com/2009/03/31/real-programming-with-php-53-part-2-javascript-style-classes/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>
