<?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>Tudor Barbu&#039;s professional blog &#187; extreme php</title>
	<atom:link href="http://blog.motane.lu/tag/extreme-php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.motane.lu</link>
	<description>Ramblings about software development</description>
	<lastBuildDate>Thu, 02 Feb 2012 17:38:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Multiple inheritance in PHP</title>
		<link>http://blog.motane.lu/2012/01/21/multiple-inheritance-in-php/</link>
		<comments>http://blog.motane.lu/2012/01/21/multiple-inheritance-in-php/#comments</comments>
		<pubDate>Sat, 21 Jan 2012 12:32:06 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[extreme php]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1878</guid>
		<description><![CDATA[I wrote yesterday an article introducing Cosmin&#8217;s blog. His most recent article is on multiple inheritance and how easy it would be to implement that into weakly typed like PHP. Just have a look at the article. Having learned OOP in Java, I am generally against multiple inheritance. I believe that if the answer is [...]]]></description>
			<content:encoded><![CDATA[<p>I wrote yesterday an article introducing Cosmin&#8217;s blog. His <a href="http://cosmi.nu/multiple-inheritance-suddenly-more-easy-in-php-than-in-c/45" title="Multiple inheritance suddleny more easy in PHP than in C" class="outgoing">most recent article</a> is on multiple inheritance and how easy it would be to implement that into weakly typed like PHP. Just have a look at the article.</p>
<p>Having learned OOP in Java, I am generally against multiple inheritance. I believe that if the answer is multiple inheritance, you&#8217;re asking the wrong question. But, for &#8220;academic&#8221; reasons, I tried to implement multiple inheritance in PHP. And I came up with the following abomination.</p>
<p>First, create a parent class from which all classes in need of multiple inheritance extend. The parent classes will be placed in the $_parents array as strings. When the main object is instantiated, the constructor creates objects from all the parent classes. And by using __call() I&#8217;m just going to redirect method calls on the main object to the first suitable parent object. I know it sounds complicated, so long story short, just read the code! I&#8217;m a developer, not a writer!</p>
<pre class="brush: php; title: ; notranslate">
/**
 * Abomination class implementing multiple inheritance via
 * __call magic method
 */
abstract class MultipleInheritance
{
    /**
     * List of parent classes
     *
     * @var array
     * @access protected
     */
    protected $_parents = array();    

    /**
     * List of parent objects - generated automatically
     *
     * @var array
     * @access private
     */
    private $_parentObjects = array();

    /**
     * Constructor (thank you captain Obvious)
     *
     * - init the parent objects
     *
     * @access public
     */
    public function __construct()
    {
        foreach ($this-&gt;_parents as $parentClass) {
            $this-&gt;_parentObjects []= new $parentClass();
        }
    }

    /**
     * __call magic method
     *
     * @param string $name
     * @param array $arguments
     * @access public
     * @return mixed
     */
    public function __call($name, array $arguments)
    {
        foreach ($this-&gt;_parentObjects as $object) {
            if (method_exists($object, $name)) {
                return call_user_func_array(array($object, $name), $arguments);
            }
        }

        throw new Exception('No such method: ' . $name);
    }
}
</pre>
<p>Now, some very sexist implementations of Mom and Dad classes:</p>
<pre class="brush: php; title: ; notranslate">
class Dad
{
    /**
     * Can parallel park
     *
     * @access public
     * @return void
     */
    public function park()
    {
        echo 'Look, I can parallel park' . PHP_EOL;
    }    

    /**
     * Can ground the kids
     *
     * @access public
     * @return void
     */
    public function ground()
    {
        echo 'Grounded by DAD' . PHP_EOL;
    }
}

class Mom
{
    protected $_parents = array('GrandMa');

    /**
     * Makes sandwiches
     *
     * @access public
     * @return void
     */
    public function makeSandwich()
    {
        echo 'Just making a sandwich' . PHP_EOL;
    }    

    /**
     * Can grounds the kids
     *
     * @access public
     * @return void
     */
    public function ground()
    {
        echo 'Grounded by MOM' . PHP_EOL;
    }
}
</pre>
<p>&#8230;and finally the child class:</p>
<pre class="brush: php; title: ; notranslate">
class Child extends MultipleInheritance
{
    protected $_parents = array('Dad', 'Mom');
}
</pre>
<p>Let&#8217;s try it out:</p>
<pre class="brush: php; title: ; notranslate">
$child = new Child();
$child-&gt;park();
$child-&gt;makeSandwich();
$child-&gt;ground();
</pre>
<p>And it works. And when two parent classes have the same method &#8211; ground() in this case &#8211; the method belonging to the first encountered class is executed. And voila, multiple inheritance in PHP. Well, sort of.</p>
<p>Now there&#8217;s a small problem with the <strong>instanceof</strong> operator. And by small problem I mean it doesn&#8217;t work and there&#8217;s no way to fix it. The following code</p>
<pre class="brush: php; title: ; notranslate">
if ($child instanceof Mom) {
    echo get_class($child) . ' class inherits from Mom' . PHP_EOL;
} else {
    echo get_class($child) . ' class does not inherit from Mom' . PHP_EOL;
}
</pre>
<p>will always go on the &#8220;else&#8221; branch, although in my application&#8217;s logic, the Child class extends from the Mom class. And since PHP doesn&#8217;t allow overloading the operators, there&#8217;s no clean way to do this. Of course, there&#8217;s a hacky way around it, by adding an isInstanceOf() method to the MultipleInheritance class:</p>
<pre class="brush: php; title: ; notranslate">
abstract class MultipleInheritance
{
    // ...

    /**
     * Check inheritance
     *
     * @param string $class
     * @access public
     * @return bool
     */
    public function isInstanceOf($class)
    {
        if (in_array($this-&gt;_parents, $class)) {
            return true;
        }

        foreach ($this-&gt;_parentObjects as $parent) {
            if ($parent instanceof MultipleInheritance) {
                if ($parent-&gt;isInstanceOf($class)) {
                    return true;
                }
            }
        }

        return false;
    }
}
</pre>
<p>&#8230;and using it to check inheritance:</p>
<pre class="brush: php; title: ; notranslate">
if ($child-&gt;isInstanceOf('Mom')) {
    echo get_class($child) . ' class inherits from Mom' . PHP_EOL;
} else {
    echo get_class($child) . ' class does not inherit from Mom' . PHP_EOL;
}
</pre>
<p>But the abomination is not completed yet. Because I used <a href="http://php.net/manual/en/function.method-exists.php" title="method_exists() in the PHP manual" class="outgoing">method_exists()</a> instead of <a href="http://php.net/manual/en/function.is-callable.php" title="is_callable() in the PHP manual" class="outgoing">is_callable()</a>, magic methods in the parent class will not be detected. To fix this, just change the code from:</p>
<pre class="brush: php; title: ; notranslate">
if (method_exists($object, $name)) {
    return call_user_func_array(array($object, $name), $arguments);
}
</pre>
<p>&#8230;to&#8230;</p>
<pre class="brush: php; title: ; notranslate">
if (is_callable($object, $name)) {
    return call_user_func_array(array($object, $name), $arguments);
}
</pre>
<p>&#8230;and it will work. At last, the abomination is ready. Doctor Frankenstein would be proud! Here is a gist with the entire example: <a href="https://gist.github.com/1652646" title="Go to https://gist.github.com/1652646" class="outgoing">https://gist.github.com/1652646</a>.</p>
<p>PS: DO NOT USE MULTIPLE INHERITANCE IN REAL LIFE APPLICATIONS!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2012/01/21/multiple-inheritance-in-php/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Accessing a method defined in the current class&#8217; &#8220;granpa&#8221;</title>
		<link>http://blog.motane.lu/2010/08/04/accessing-a-method-defined-in-the-current-class-granpa/</link>
		<comments>http://blog.motane.lu/2010/08/04/accessing-a-method-defined-in-the-current-class-granpa/#comments</comments>
		<pubDate>Wed, 04 Aug 2010 09:18:29 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[extreme php]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1410</guid>
		<description><![CDATA[Problem: we have an hierarchy of 3 classes, each extending the one in front (grandfather, father, son). A method &#8211; let&#8217;s say foo() &#8211; is defined in the grandfather class and overridden with a new functionality in the father class. Question: Is there a way in the son class to access the original method (with [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Problem</strong>: we have an hierarchy of 3 classes, each extending the one in front (grandfather, father, son). A method &#8211; let&#8217;s say <em>foo()</em> &#8211; is defined in the <em>grandfather</em> class and overridden with a new functionality in the <em>father</em> class.</p>
<p><strong>Question</strong>: Is there a way in the <em>son</em> class to access the original method (with the grandfather code) in the son class?</p>
<p>Of course, the obvious solution is to try something like:</p>
<pre class="brush: php; title: ; notranslate">
parent::parent::method();
</pre>
<p>But it won&#8217;t work. It will just yield an error like:</p>
<blockquote><p>Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in &#8230;</p></blockquote>
<p>After some struggling, I have found a way to get around and access a method from the <em>grandparent</em> class that was overridden in the <em>parent</em> and run its &#8220;original&#8221; code. It&#8217;s loosely based on the strange PHP scoping that I wrote about in <a href="http://blog.motane.lu/2010/05/11/strange-php-scoping/" title="Strange PHP scoping">this article</a>. The approach goes something like this:</p>
<pre class="brush: php; title: ; notranslate">
class Grandfather
{
    protected $_message = 'Luke, I am your grandfather';

    public function say()
    {
        echo $this-&gt;_message;
    }
}

class Father extends Grandfather
{
    protected $_message = 'Luke, I am your father';   

    public function say()
    {
        throw new Exception(&quot;I can't breath under this f**cking mask <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> &quot;);
    }
}

class Son extends Father
{
    protected $_message = 'I have a very bad feeling about this';

    public function say()
    {
        Grandfather::say();
    }
}

$son = new Son();
$son-&gt;say();
</pre>
<p>Now PHP will bind the <em>$this </em>pointer in the body of the <em>say()</em> method &#8211; using the code defined in the grandfather. I guess that weird scoping is there for a reason.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/08/04/accessing-a-method-defined-in-the-current-class-granpa/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Remove empty array elements with recursive lambda in PHP 5.3</title>
		<link>http://blog.motane.lu/2010/06/17/remove-empty-array-elements-with-recursive-lambda-in-php-5-3/</link>
		<comments>http://blog.motane.lu/2010/06/17/remove-empty-array-elements-with-recursive-lambda-in-php-5-3/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 16:08:52 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[extreme php]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[php 5.3]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1393</guid>
		<description><![CDATA[How do you remove empty elements from a PHP array? The answer&#8217;s quite simple: array_filter(). Straight from manual and works like a charm: Well, most of the time. It&#8217;s not recursive by default, so it only removes empty items on the first level of the array. If you have nested arrays and wish to remove [...]]]></description>
			<content:encoded><![CDATA[<p>How do you remove empty elements from a PHP array? The answer&#8217;s quite simple: <a href="http://php.net/manual/en/function.array-filter.php" title="array_filter() in PHP's manual" class="outgoing">array_filter()</a>. Straight from manual and works like a charm:</p>
<pre class="brush: php; title: ; notranslate">
$filtered = array_filter($raw);
</pre>
<p>Well, most of the time. It&#8217;s not recursive by default, so it only removes empty items on the first level of the array. If you have nested arrays and wish to remove all the empty items, regardless of their position in the matrix, array_filter() won&#8217;t work.</p>
<p>For example, let&#8217;s consider the following construct:</p>
<pre class="brush: php; title: ; notranslate">
$raw = array(
    'firstname' =&gt; 'Foo',
    'lastname'  =&gt; 'Bar',
    'nickname' =&gt; '',
    'birthdate' =&gt; array(
        'day'   =&gt; '',
        'month' =&gt; '',
        'year'  =&gt; '',
    ),
    'likes' =&gt; array(
        'cars'  =&gt; array('Subaru Impreza WRX STi', 'Mitsubishi Evo', 'Nissan GTR'),
        'bikes' =&gt; array(),
    ),
);
</pre>
<p>In this case, PHP&#8217;s built in array_filter() will miss the &#8220;birthdate&#8221; and &#8220;bikes&#8221; items. So, what now? Of course, you can create a function that will remove empty items recursively and pass it as a callback to PHP&#8217;s array_filter() function:</p>
<pre class="brush: php; title: ; notranslate">
function removeEmptyItems($item)
{
    if (is_array($item)) {
        return array_filter($item, 'removeEmptyItems');
    }

    if (!empty($item)) {
        return true;
    }
}

$filtered = array_filter($raw, 'removeEmptyItems');
</pre>
<p>But if you&#8217;re using a framework like Zend Framework that forbids using functions in the global scope and asks that all functions are wrapped in classes as static methods, things become more complicated and verbose. Yeah, yeah, I know, I&#8217;m a standards nazi <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>But if you&#8217;re using PHP 5.3, there&#8217;s a much simpler solution:</p>
<pre class="brush: php; title: ; notranslate">
$callback = function($item) use (&amp;$callback) {
    if (is_array($item)) {
        return array_filter($item, $callback);
    }
    if (!empty($item)) {
        return true;
    }
};

$filtered = array_filter($raw, $callback);
</pre>
<p>Lambdas are sweet <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/06/17/remove-empty-array-elements-with-recursive-lambda-in-php-5-3/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Strange PHP scoping</title>
		<link>http://blog.motane.lu/2010/05/11/strange-php-scoping/</link>
		<comments>http://blog.motane.lu/2010/05/11/strange-php-scoping/#comments</comments>
		<pubDate>Tue, 11 May 2010 07:03:23 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[extreme php]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[theoretical issues]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1360</guid>
		<description><![CDATA[I came to the conclusion that PHP is the programing language with the weirdest features. After the variable variables mess, that allows to you to name your variables stuff like !@#$%^&#038;*()_+= and not be able to use them directly, I thought I saw everything. But no, yesterday I&#8217;ve bumped in another strange PHP feature. An [...]]]></description>
			<content:encoded><![CDATA[<p>I came to the conclusion that PHP is the programing language with the weirdest features. After the <a href="http://blog.motane.lu/2009/02/03/dynamic-variables-in-php/" title="Variable variables in PHP">variable variables</a> mess, that allows to you to name your variables stuff like <strong>!@#$%^&#038;*()_+=</strong> and not be able to use them directly, I thought I saw everything. But no, yesterday I&#8217;ve bumped in another strange PHP feature. An even stranger feature.</p>
<p>Take a look at the code below:</p>
<pre class="brush: php; title: ; notranslate">
class Example
{
    public function dynamicMethod($string)
    {
        // calls method baz() of the same class
        // class Example *does not have* a baz() method
        $this-&gt;baz($string);
    }
}

class Foo
{
    public function bar()
    {
        // a dynamic method called statically
        // no Example object is being instantiated
        Example::dynamicMethod('whatever');
    }

    public function baz($string)
    {
        echo 'Method baz() called with param &quot;' . $string . '&quot;' . PHP_EOL;
    }
}

$foo = new Foo();
$foo-&gt;bar();
</pre>
<p>What do you think the code will do? Yield an exception? A syntax error? Work? Well, strangely enough, it works:</p>
<pre class="brush: plain; title: ; notranslate">
Tudor-Barbus-MacBook% php blog-example.php
Method baz() called with param &quot;whatever&quot;
</pre>
<p>&#8230;and it seems that this feature is here to stay and be supported in the future, since I&#8217;m using the new PHP 5.3 version:</p>
<pre class="brush: plain; title: ; notranslate">
Tudor-Barbus-MacBook% php -v
PHP 5.3.1 (cli) (built: Feb 11 2010 02:32:22)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies
</pre>
<p>I wonder how this can be useful to somebody.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/05/11/strange-php-scoping/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Logical operators in PHP</title>
		<link>http://blog.motane.lu/2009/04/03/logical-operators-in-php/</link>
		<comments>http://blog.motane.lu/2009/04/03/logical-operators-in-php/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 07:25:41 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[extreme php]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=401</guid>
		<description><![CDATA[Early in his career, every PHP programmer writes code like: Come on! We&#8217;ve all been there. Of course, now we all agree that that&#8217;s lame and stupid and we use PDO or even ActiveRecord, but back in the days, that was widely used. What does that mean, actually? or die()? It&#8217;s an optimization originally implemented [...]]]></description>
			<content:encoded><![CDATA[<p>Early in his career, every PHP programmer writes code like:</p>
<pre class="brush: php; title: ; notranslate">
mysql_query( $sql ) or die( mysql_error() );
</pre>
<p>Come on! We&#8217;ve all been there. Of course, now we all agree that that&#8217;s lame and stupid and we use PDO or even ActiveRecord, but back in the days, that was widely used. What does that mean, actually? <code>or die()</code>?</p>
<p>It&#8217;s an optimization originally implemented in C++ &#8211; I think &#8211; gone wild.</p>
<p>For instance, if you have a condition like:</p>
<pre class="brush: php; title: ; notranslate">
if ( ( $a == $b ) || ( $c == $d ) ) { /* whatever */}
</pre>
<p>&#8230;if the the result in the first set of parenthesis evaluates to true, the second one isn&#8217;t evaluated because its result is irrelevant in this context. The parser already knows the answer, as &#8220;true or anything&#8221; always equals true.</p>
<p>The <a href="http://php.net/mysql_query" title="mysql_query() in PHP manual" class="outgoing">mysql_query()</a> function returns a value that can be evaluated from a boolean point of view. If that result is evaluated to true (the query was okay), then the die() part gets left out. If the query fails and mysql_query() returns something that evaluates as false, then the die() call gets executed. That&#8217;s all, in a nutshell.</p>
<p>The above code could have been rewritten as:</p>
<pre class="brush: php; title: ; notranslate">
if ( ! mysql_query( $sql ) ) {
    die( mysql_error() );
}
</pre>
<p>Still lame, but with improved readability. </p>
<p>Of course, you can do nifty tricks with this kind of constructs:</p>
<pre class="brush: php; title: ; notranslate">
is_numeric ( $_GET['id'] ) || redirect( '/my/error/url' );
</pre>
<p>Cool!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2009/04/03/logical-operators-in-php/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Dynamic or variable variables in PHP</title>
		<link>http://blog.motane.lu/2009/02/03/dynamic-variables-in-php/</link>
		<comments>http://blog.motane.lu/2009/02/03/dynamic-variables-in-php/#comments</comments>
		<pubDate>Tue, 03 Feb 2009 21:56:09 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[extreme php]]></category>
		<category><![CDATA[funny programming]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=284</guid>
		<description><![CDATA[Variable variables (or their official name &#8211; pointed out by Ionut Stan in the comments) or &#8220;dynamic variables&#8221; (how I like to call them) is the name of a feature of the PHP programming language which allows a programmer to define a variable that has its name given by the content of another variable. Like [...]]]></description>
			<content:encoded><![CDATA[<p>Variable variables (or their official name &#8211; pointed out by Ionut Stan in the comments) or &#8220;dynamic variables&#8221; (how I like to call them) is the name of a feature of the PHP programming language which allows a programmer to define a variable that has its name given by the content of another variable. Like such: </p>
<pre class="brush: php; title: ; notranslate">
$foo = 'bar';
/*
 * declare a variable called bar into the
 * current scope and initialise it with Hello world
 */
$$foo = 'Hello world';

echo $bar; // will echo Hello world
</pre>
<p>If find this really useless and very annoying, because a typo such as a double dollar sign in front of a variable can result in some very hard to track bugs. But this isn&#8217;t just another strange feature that made its way into the trunk. This is very, very well implemented and some programmers strived a lot to make it work under all possible circumstances. It works so well that you can use strings that cannot be normally used to represent variable names, such as !@#$%^&#038;*()_+-=/*. Really, it works! </p>
<pre class="brush: php; title: ; notranslate">
$foo = '!@#$%^&amp;*()_+-=/*';
$$foo = 'Hello world';

$variables = get_defined_vars();
echo $variables['!@#$%^&amp;*()_+-=/*'];
/**
 * will echo Hello world - the content of a variable called !@#$%^&amp;*()_+-=/*
 */
</pre>
<p>Further more, it even works with objects:</p>
<pre class="brush: php; title: ; notranslate">
class Example {
     /**
      * sample attribute
      *
      * @var string
      */
     private $value;

     /**
      * default constructor
      *
      * @param $_value
      */
     public function __construct( $_value ) {
          $this-&gt;value = (string) $_value;
     }

     /**
      * returns a string representation
      * of this object
      *
      * @return string
      */
     public function __toString() {
          return $this-&gt;value;
     }
}

$foo = new Example( 'bar' );
$$foo = 'Hello world';

echo $bar; // will echo Hello world
</pre>
<p>I think this one of those features reserved for the most gurus of the gurus, because after 5 years experience with PHP and a Zend Certification, I haven&#8217;t yet grasped the logic behind this&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2009/02/03/dynamic-variables-in-php/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Multithreading in php</title>
		<link>http://blog.motane.lu/2009/01/02/multithreading-in-php/</link>
		<comments>http://blog.motane.lu/2009/01/02/multithreading-in-php/#comments</comments>
		<pubDate>Thu, 01 Jan 2009 23:56:21 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[extreme php]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=40</guid>
		<description><![CDATA[Some time ago, I&#8217;ve wrote a small server in PHP. Nothing fancy. It would listen on a socket and when a new client would connect, the server would start a new thread and manage the client&#8217;s request. Since threading it&#8217;s not available in PHP, I&#8217;ve emulated the threads with child processes which are available in [...]]]></description>
			<content:encoded><![CDATA[<p>Some time ago, I&#8217;ve wrote a small server in PHP. Nothing fancy. It would listen on a socket and when a new client would connect, the server would start a new thread and manage the client&#8217;s request. Since threading it&#8217;s not available in PHP, I&#8217;ve emulated the threads with child processes which are available in php. A thread object simply encapsulates a new process started with <a href="http://www.php.net/pcntl_fork" title="pnctl_fork() in the php manual" class="outgoing">pnctl_fork()</a> and emulates &#8211; to some extent &#8211; the behaviour of the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html" title="Thread class in Java" class="outgoing">java.lang.Thread</a> class, the main difference being that in my implementation, you don&#8217;t extend the Thread class, you simply provide the name of a callback function in the constructor. </p>
<p>A simple multithreaded application would look like this:</p>
<pre class="brush: php; title: ; notranslate">
require_once( 'Thread.php' );

// test to see if threading is available
if( ! Thread::available() ) {
	die( 'Threads not supported' );
}

// function to be ran on separate threads
function paralel( $_limit, $_name ) {
	for ( $index = 0; $index &lt; $_limit; $index++ ) {
		echo 'Now running thread ' . $_name . PHP_EOL;
		sleep( 1 );
	}
}

// create 2 thread objects
$t1 = new Thread( 'paralel' );
$t2 = new Thread( 'paralel' );

// start them
$t1-&gt;start( 10, 't1' );
$t2-&gt;start( 10, 't2' );

// keep the program running until the threads finish
while( $t1-&gt;isAlive() &amp;&amp; $t2-&gt;isAlive() ) {

}
</pre>
<p>This will display <em>Now running thread 1</em> and <em>Now running thread 2</em> messages with 1 second delays. I know, not that impressive, but hey, it&#8217;s multithreaded.<span id="more-40"></span></p>
<p>PHP threading will only work on Unix and Linux systems, because pnctl_fork is nothing more than a wrapper for the fork() function from <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/unistd.h.html" title="unistd.h specs" class="outgoing">unistd.h</a> and it&#8217;s not available under Microsoft operating systems. </p>
<p>I know that the first example was pretty lame, but there are some more interesting things you could do with threads in PHP. For instance, if you need to do some server side processing of all the images in a directory, a multithreaded approach will be much faster.</p>
<pre class="brush: php; title: ; notranslate">
require_once( 'Thread.php' );

// test to see if threading is available
if( ! Thread::available() ) {
	die( 'Threads not supported' );
}

// define the function to be run as a separate thread
function processImage( $_image ) {
	// expensive image processing logic here
}

$threads = array();
$index = 0;

foreach( new DirectoryIterator( '/path/to/images' ) as $item ) {
	if( $item-&gt;isFile() ) {
		$threads[$index] = new Thread( 'processImage' );
		$threads[$index]-&gt;start( $item-&gt;getPathname() );
		++$index;
        }
}

// wait for all the threads to finish
while( !empty( $threads ) ) {
	foreach( $threads as $index =&gt; $thread ) {
		if( ! $thread-&gt;isAlive() ) {
			unset( $threads[$index] );
		}
	}
	// let the CPU do its work
	sleep( 1 );
}
</pre>
<p>PS: it&#8217;s a bad practice to keep looping in order to wait for a thread to finish. An  ongoing empty loop will quickly boost your CPU &#8216;s load to 100%. If you need your processor free (and you need it), simply send the current (looping) thread to <a href="http://www.php.net/manual/en/function.sleep.php" title="sleep() in the php manual">sleep</a> and let the others execute.</p>
<pre class="brush: php; title: ; notranslate">
// wait for thread - bad approach (overloads the CPU)
while ( $thread-&gt;isAlive() ) {
}

// wait for thread - correct approach
while( $thread-&gt;isAlive() ) {
    sleep( 1 );
}
</pre>
<h2><span>Download Thread.php</span></h2>
<p>Here you go: <a href="http://downloads.motane.lu/Thread.php" title="Download Thread.php" class="download">Thread.php</a>. Just click the link to download the class. If you have a better approach to this issue or think that the original class could be improved, don&#8217;t be shy and leave a comment below. Credits will be given.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2009/01/02/multithreading-in-php/feed/</wfw:commentRss>
		<slash:comments>67</slash:comments>
		</item>
	</channel>
</rss>

