<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7750105339598410554</id><updated>2026-03-25T12:27:13.437-07:00</updated><category term="-"/><category term="implied"/><category term="implied class"/><category term="php"/><category term="php pattern"/><title type='text'>.PHP</title><subtitle type='html'>Some PHP Snippets and ideas</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://dot-php.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://dot-php.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>9</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7750105339598410554.post-6514891639646524695</id><published>2010-04-06T17:34:00.000-07:00</published><updated>2010-04-06T17:37:32.449-07:00</updated><title type='text'>Eval string with PHP tags</title><content type='html'>Here is another non-obvious twist on PHP.&lt;br /&gt;
&lt;br /&gt;
I have been trying to evaluate tags in a php string without having to run preg_match or do any other kind of parsing. So I read some articles that propose this:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush:php&quot;&gt;eval(&#39;?&amp;gt;&#39; . $sMyStringWithPHPTagsInIt . &#39;&amp;lt;?&#39;);
&lt;/pre&gt;&lt;br /&gt;
This works, since eval implicitly opens up php tags around evaluated code.&lt;br /&gt;
However, it outputs the result to the STDOUT. This is not helpful when you need to do additional operations on the string after the evaluation.&lt;br /&gt;
&lt;br /&gt;
So, I came up with this:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush:php&quot;&gt;function evalFile($sFileName) {
 ob_start();
 ob_flush();
 eval(&#39;?&amp;gt;&#39; . file_get_contents($sFileName) . &#39;&amp;lt;?&#39;);
 $s = ob_get_contents();
 ob_clean();
 return $s;  
}
&lt;/pre&gt;&lt;br /&gt;
It grabs the buffer from STDOUT and returns it into a string. The only problem is that it would have to flush the current contents of the buffer. If someone has a better solution, please post it here.</content><link rel='replies' type='application/atom+xml' href='http://dot-php.blogspot.com/feeds/6514891639646524695/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/7750105339598410554/6514891639646524695' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/6514891639646524695'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/6514891639646524695'/><link rel='alternate' type='text/html' href='http://dot-php.blogspot.com/2010/04/eval-string-with-php-tags.html' title='Eval string with PHP tags'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7750105339598410554.post-942295066983695988</id><published>2010-03-22T15:01:00.000-07:00</published><updated>2010-03-22T15:01:13.944-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="-"/><title type='text'>Image class</title><content type='html'>Ok, here I go. The very first violation of my own rule - not posting anything obvious.&lt;br /&gt;
This time however I needed to find a good class Image that works with GD and is designed nicely. After 10 min of search I decided to write my own. So, for the lack of better place, I will put it here. If you are not into the obvious - skip this post.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;&amp;lt;?

 /**
  * Class Image
  * @author Alexander Podgorny
  * @license GPL
  */

 class Image {
  const RESIZE_FILL   = 2; // When resizing, constrain proportions, keep largest dimension
  const RESIZE_FIT  = 3; // When resizing, constrain proportions, keep smallest dimension
  const RESIZE_STRETCH  = 1; // When resizing, do not constrain proportions, keep both dimensions
  
  const TYPE_JPEG   = 10;
  const TYPE_GIF   = 11;
  const TYPE_PNG   = 12;
  
  private $_sFileName = &#39;&#39;;
  private $_oImage  = null;
  private $_nW   = 0;
  private $_nH  = 0;
  
  public function __construct($sFileName=null) {
   if ($sFileName) {
    $this-&gt;open($sFileName);
   }
  }
  
  public function __destruct() {
   imagedestroy($this-&gt;_oImage);
  }
  
  public function open($sFileName) {
   if (!file_exists($sFileName)) {
    throw new Exception(&#39;File could not be found: &#39;.$sFileName);
   }
   $this-&gt;_sFileName  = $sFileName;
   $sExtension   = strtolower(strrchr($sFileName, &#39;.&#39;));
   switch ($sExtension) {
          case &#39;.jpg&#39;:
          case &#39;.jpeg&#39;:
              $this-&gt;_oImage = imagecreatefromjpeg($sFileName);
              break;
          case &#39;.gif&#39;:
              $this-&gt;_oImage = imagecreatefromgif($sFileName);
              break;
          case &#39;.png&#39;:
              $this-&gt;_oImage = imagecreatefrompng($sFileName);
              break;
          default:
     throw new Exception(&#39;Unknown file type: &#39;.$sFileName);
      }   
   $this-&gt;_nW   = imagesx($this-&gt;_oImage);
   $this-&gt;_nH  = imagesy($this-&gt;_oImage);
   return $this;
  }
  
  public function resize($nW, $nH, $nOption=self::RESIZE_FIT) {
   $nSrcRatio = $this-&gt;_nW / $this-&gt;_nH;
   $nDstRatio = $nW / $nH;
   
   switch ($nOption) {
    case self::RESIZE_STRETCH:
     // do nothing;
     break;
    case self::RESIZE_FILL:
     if ($nDstRatio &gt; $nSrcRatio) {
      $nH = $nW / $nSrcRatio;
     } else {
      $nW = $nSrcRatio * $nH;
     }
     break;
    case self::RESIZE_FIT:
    default:
     if ($nDstRatio &gt; $nSrcRatio) {
      $nW = $nSrcRatio * $nH;
     } else {
      $nH = $nW / $nSrcRatio;
     }
     break;
   }
   $nW = floor($nW);
   $nH = floor($nH);
   $oImageResized = imagecreatetruecolor($nW, $nH);
   imagecopyresampled(
    $oImageResized, 
    $this-&gt;_oImage, 
    0, 0, 0, 0, 
    $nW, 
    $nH, 
    $this-&gt;_nW, 
    $this-&gt;_nH
   );
   imagedestroy($this-&gt;_oImage);
   $this-&gt;_oImage = $oImageResized;
   $this-&gt;_nW = $nW;
   $this-&gt;_nH = $nH;
   return $this;
  }
  
  public function save($sFileName=null, $nQuality=null) {
   if (!$sFileName) { $sFileName = $this-&gt;_sFileName; }
   $sExtension   = strtolower(strrchr($sFileName, &#39;.&#39;));
   if (!$sFileName) {
    throw new Exception(&#39;Could not save file. File name is not supplied&#39;);
   }
   switch ($sExtension) {
          case &#39;.jpg&#39;:
          case &#39;.jpeg&#39;:
           if ($nQuality !== null) {  // otherwise use built in default
      if ($nQuality &lt; 0)   { $nQuality = 0; }
            if ($nQuality &gt; 100) { $nQuality = 100; }
           }
              imagejpeg($this-&gt;_oImage, $sFileName, $nQuality);
              break;
          case &#39;.gif&#39;:
              imagegif($this-&gt;_oImage, $sFileName);
              break;
          case &#39;.png&#39;:
           if ($nQuality !== null) {  // otherwise use built in default
      if ($nQuality &gt; 9) { $nQuality = 9; }
      if ($nQuality &lt; 0) { $nQuality = 0; }
           }
              imagepng($this-&gt;_oImage, $sFileName, $nQuality);
              break;
          default:
     throw new Exception(&#39;Unknown file type: &#39;.$sFileName);
     break;
      }   
   return $this;
  }
  
  public function output($nType=self::TYPE_JPEG, $nQuality=null) {
   switch ($nType) {
          case self::TYPE_JPEG:
           if ($nQuality) {  // otherwise use built in default
      if ($nQuality &lt; 0)   { $nQuality = 0; }
            if ($nQuality &gt; 100) { $nQuality = 100; }
           }
           header(&#39;Content-type: image/jpeg&#39;);
              imagejpeg($this-&gt;_oImage, null, $nQuality);
              break;
          case self::TYPE_GIF:
           header(&#39;Content-type: image/gif&#39;);
              imagegif($this-&gt;_oImage, null);
              break;
          case self::TYPE_PNG:
           if ($nQuality) {  // otherwise use built in default
      if ($nQuality &gt; 9) { $nQuality = 9; }
      if ($nQuality &lt; 0) { $nQuality = 0; }
           }
           header(&#39;Content-type: image/png&#39;);
              imagepng($this-&gt;_oImage, null, $nQuality);
              break;
          default:
     throw new Exception(&#39;Unknown file type&#39;);
     break;
      }   
   return $this;
  }
  
 }

?&amp;gt;
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://dot-php.blogspot.com/feeds/942295066983695988/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/7750105339598410554/942295066983695988' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/942295066983695988'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/942295066983695988'/><link rel='alternate' type='text/html' href='http://dot-php.blogspot.com/2010/03/image-class.html' title='Image class'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7750105339598410554.post-60610581157398736</id><published>2010-03-07T13:37:00.000-08:00</published><updated>2010-03-11T17:17:43.428-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="implied"/><category scheme="http://www.blogger.com/atom/ns#" term="implied class"/><category scheme="http://www.blogger.com/atom/ns#" term="php"/><category scheme="http://www.blogger.com/atom/ns#" term="php pattern"/><title type='text'>Implied Class Pattern with __autoload()</title><content type='html'>One more thing about not-so-obvious capabilities of PHP: &lt;b&gt;Implied Class Pattern&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s say you are implementing a Model layer in your MVC where each model class corresponds to one table. So if your table name is &quot;member&quot; than you might want to have class MemberModel. Then you create table &quot;city&quot;, then &quot;state&quot;, then forty more tables. So you end up with forty more classes that share exactly the same functionality with one only difference: table name.&lt;br /&gt;
&lt;br /&gt;
Here is how every one of your files might look like: &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;&amp;lt;?php
    class MemberModel extends Model {}
?&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Of course you will try to use &lt;a href=&quot;http://php.net/manual/en/language.oop5.autoload.php&quot;&gt;__autoload()&lt;/a&gt; to dynamically load them at run time.&lt;br /&gt;
But loading extra forty (or more) files translates into reading from the disk just as many times. Not the most efficient solution.&lt;br /&gt;
&lt;br /&gt;
Another inefficient thing about this approach is having to write those files every time you add a table to your database.&lt;br /&gt;
&lt;br /&gt;
All of this can be avoided with &lt;b&gt;Implied Class Pattern&lt;/b&gt;. Consider the following code:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;function __autoload($sClassName) {
    $bLoaded = false;
    foreach ($_ENV[&#39;AUTOLOAD_PATHS&#39;] as $sAutoloadPath) {
        $sFilePath = $sAutoloadPath.$sClassName.&#39;.php&#39;;
        if (file_exists($sFilePath)) {
            require_once $sFilePath;
            $bLoaded = true;
            break;
        }
    }
    if (!$bLoaded) {
        // Implied classes
        if (preg_match(&#39;/Model$/&#39;, $sClassName)) {
            eval(&quot;class $sClassName extends Model {}&quot;);
        } else {
            throw new Exception(&#39;Class &#39;.$sClassName.&#39; not found&#39;);
        }
    }
}
&lt;/pre&gt;&lt;br /&gt;
This way whenever you need a specific subclass of Model it is created for you &quot;on-the-fly&quot; avoiding multiple redundant files and disk activity.&lt;br /&gt;
&lt;br /&gt;
Of course if you need to add a model-specific functionality, you can always add that extra file into your autoloaded directory and it will load the implemented class before it tries to imply it. So win-win.&lt;br /&gt;
&lt;br /&gt;
To summarize: Where do you use &lt;b&gt;Implied Class Pattern?&lt;/b&gt; Whenever you have multiple subclasses of one base class with little or no difference from one another.&lt;br /&gt;
&lt;br /&gt;
Enjoy.</content><link rel='replies' type='application/atom+xml' href='http://dot-php.blogspot.com/feeds/60610581157398736/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/7750105339598410554/60610581157398736' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/60610581157398736'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/60610581157398736'/><link rel='alternate' type='text/html' href='http://dot-php.blogspot.com/2010/03/implied-class-pattern-with-autoload.html' title='Implied Class Pattern with __autoload()'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7750105339598410554.post-296747163032793501</id><published>2010-03-02T19:13:00.000-08:00</published><updated>2010-03-11T17:19:15.145-08:00</updated><title type='text'>Wrapping it up nicely :: Base Object :: Part 6</title><content type='html'>So, now we have the whole library. Now we need a name. I will call it dotPHP. Just because I like the name.&lt;br /&gt;
&lt;br /&gt;
Now, why not even do the definition and extension in one line of code? I will define a DotPHP class to help us contain it all within a nice namespace:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;class DotPHP {
        public static function defineClass($sClassName, $mBase=null) {
            eval(&#39;class &#39;.$sClassName.&#39; extends Object {}&#39;);
            if ($mBase) {
                $sClassName::extend($mBase);
            }
        }
    }
&lt;/pre&gt;&lt;br /&gt;
Now the all the code is done in a fewer lines of code:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;DotPHP::defineClass(&#39;A&#39;, array(
        &#39;method3&#39; =&gt; function($owner) { print &#39;method3&#39;; }
    ));
    DotPHP::defineClass(&#39;B&#39;, &#39;A&#39;);
    
    print $o2-&gt;method3(); // output: method3
&lt;/pre&gt;&lt;br /&gt;
Please leave some feedback so that I know if you guys like the syntax.</content><link rel='replies' type='application/atom+xml' href='http://dot-php.blogspot.com/feeds/296747163032793501/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/7750105339598410554/296747163032793501' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/296747163032793501'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/296747163032793501'/><link rel='alternate' type='text/html' href='http://dot-php.blogspot.com/2010/03/wrapping-it-up-nicely-base-object-part.html' title='Wrapping it up nicely :: Base Object :: Part 6'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7750105339598410554.post-2540838277284484467</id><published>2010-03-02T18:23:00.000-08:00</published><updated>2010-03-11T17:20:30.241-08:00</updated><title type='text'>Extending PHP classes at run time :: Base Object :: Part 5</title><content type='html'>In part 4 of this article we have extended objects at run time. Now wouldn&#39;t it be nice if we could do the same with classes? Also at run time.&lt;br /&gt;
&lt;br /&gt;
Sure we can. Unfortunately, the __staticCall, __staticGet and __staticSet are not implemented in PHP 5.3, so we will have to improvise while still keeping the syntax pretty.&lt;br /&gt;
&lt;br /&gt;
I am not going to list all the multiple modifications I did to the base object class, I will just dump the whole thing here, take a look:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;class Object {
        
        /**************** PRIVATE ****************/
        
        /**************** PROTECTED **************/
        
        protected static $_aClassProperties = array();
        protected $_aProperties = array();
        
        /**************** STATIC ****************/

        public static function construct() {
            $aArgs = func_get_args();
            $nArgCount = count($aArgs);
            $aArgTokens = array();
            for ($i=0; $i&amp;lt;$nArgCount; $i++) {
                $aArgTokens[] = &#39;$aArgs[&#39;.$i.&#39;]&#39;;
            }
            $sArgTokens = implode(&#39;,&#39;, $aArgTokens);
            $sEval = &#39;return new &#39;.get_called_class().&#39;(&#39;.$sArgTokens.&#39;);&#39;;
            return eval($sEval);
        }

        /**************** PUBLIC ****************/
        
        public function __construct() {
            if (!isset(self::$_aClassProperties[get_called_class()])) {
                self::$_aClassProperties[get_called_class()] = array();
            }
            $this-&amp;gt;extend(self::$_aClassProperties[get_called_class()]);
        }
        public function __call($sMethod, $aArgs) {
            if (isset($this-&amp;gt;_aProperties[$sMethod])) {
                $f = $this-&amp;gt;_aProperties[$sMethod];
                $nArgCount = count($aArgs);
                $aArgTokens = array(&#39;$this&#39;);
                for ($i=0; $i&amp;lt;$nArgCount; $i++) {
                    $aArgTokens[] = &#39;$aArgs[&#39;.$i.&#39;]&#39;;
                }
                $sArgTokens = implode(&#39;,&#39;, $aArgTokens);
                $sEval = &#39;return $f(&#39;.$sArgTokens.&#39;);&#39;;
                return eval($sEval);
            } else {
                throw new Exception(&#39;Method &#39;.$sMethod.&#39; does not exist in class &#39;.get_class($this));
            }
        }
        public function __get($sProperty) {
            return isset($this-&amp;gt;_aProperties[$sProperty]) 
                ? $this-&amp;gt;_aProperties[$sProperty] 
                : null;
        }
        public function __set($sProperty, $mValue) {
            $this-&amp;gt;_aProperties[$sProperty] = $mValue;
            return $mValue; 
        }
        public function extend($mBase) {
            $sClass = get_called_class();
            if (!isset(self::$_aClassProperties[$sClass])) {
                self::$_aClassProperties[$sClass] = array();
            }
            
            if ($this) {                             // object call
                if (!is_array($mBase)) {
                    $mBase = $mBase-&amp;gt;_aProperties;
                }
                $this-&amp;gt;_aProperties = array_merge(
                    $this-&amp;gt;_aProperties, 
                    $mBase
                );
            } else {                                 // static call
                if (is_string($mBase)) {            // class name is supplied
                    $mBase = self::$_aClassProperties[$mBase];
                }
                self::$_aClassProperties[$sClass] = array_merge(
                    self::$_aClassProperties[$sClass],
                    $mBase
                );
            }
        }
    }
&lt;/pre&gt;&lt;br /&gt;
Suffice it to say that I have made the following things possible:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;class A extends Object {};
    A::extend(array(
        &#39;method3&#39; =&amp;gt; function($owner) { print &#39;method3&#39;; }
    ));
    class B extends Object {};
    B::extend(&#39;A&#39;);
    
    $o1 = Object::construct();
    $o1-&amp;gt;method1 = function($owner) { return &#39;method1&#39;; };
    $o2 = B::construct();
    $o2-&amp;gt;method2 = function($owner) { return &#39;method2&#39;; };
    $o2-&amp;gt;extend($o1);
    print $o2-&amp;gt;method1(); // output: method1
    print $o2-&amp;gt;method2(); // output: method2
    print $o2-&amp;gt;method3(); // output: method3 
&lt;/pre&gt;&lt;br /&gt;
To rephrase the above: now we can use the same extend() method to respond to static calls. Specifically two types of static calls extend([string ClassName]) and extend([array aProperties]).&lt;br /&gt;
&lt;br /&gt;
All the properties extended at class level are copied to the object when it is instantiated. Of course if a constructor is overridden in subclass, it would have to call parent::__construct().&lt;br /&gt;
&lt;br /&gt;
Cool?</content><link rel='replies' type='application/atom+xml' href='http://dot-php.blogspot.com/feeds/2540838277284484467/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/7750105339598410554/2540838277284484467' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/2540838277284484467'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/2540838277284484467'/><link rel='alternate' type='text/html' href='http://dot-php.blogspot.com/2010/03/extending-php-classes-at-run-time-base.html' title='Extending PHP classes at run time :: Base Object :: Part 5'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7750105339598410554.post-4415453121994172854</id><published>2010-03-02T17:06:00.000-08:00</published><updated>2010-03-11T17:20:43.780-08:00</updated><title type='text'>Extending objects in PHP at run-time  ::  Base Object :: Part 4</title><content type='html'>So, on our quest to add JavaScript flexibility to PHP we need another thing common in many JS frameworks: ability to extend objects at run time.&lt;br /&gt;
&lt;br /&gt;
This is super easy based on what we have already done.&lt;br /&gt;
Add this method to your class Object:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;public function extend(Object $oAnotherObject) {
        $this-&gt;_aProperties = array_merge(
            $this-&gt;_aProperties, 
            $oAnotherObject-&gt;_aProperties
        );
    }
&lt;/pre&gt;&lt;br /&gt;
Now you can copy dynamic methods and properties from Object to Object at run time like so:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;$o1 = Object::construct();
    $o1-&gt;method1 = function($owner) { return &#39;method1&#39;; };
    $o2 = Object::construct();
    $o2-&gt;method2 = function($owner) { return &#39;method2&#39;; };
    $o2-&gt;extend($o1);
    print $o2-&gt;method1(); // output: method1
    print $o2-&gt;method2(); // output: method2
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://dot-php.blogspot.com/feeds/4415453121994172854/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/7750105339598410554/4415453121994172854' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/4415453121994172854'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/4415453121994172854'/><link rel='alternate' type='text/html' href='http://dot-php.blogspot.com/2010/03/extending-objects-in-php-at-run-time.html' title='Extending objects in PHP at run-time  ::  Base Object :: Part 4'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7750105339598410554.post-7185784907121727155</id><published>2010-03-02T15:31:00.000-08:00</published><updated>2010-03-11T17:21:12.524-08:00</updated><title type='text'>Dynamically adding methods in PHP  ::  Base Object :: Part 3</title><content type='html'>If you are a seasoned javascript developer, coding in PHP must feel like riding a bike in a straight jacket. Some of the features that you miss so much may still be added. If not through direct syntax, but through your own ingenuity.&lt;br /&gt;
&lt;br /&gt;
In this article we will enable dynamic methods. Worth mentioning that this feature will only work in PHP 5.3 since closures were added only at that point.&lt;br /&gt;
&lt;br /&gt;
So, add the following method to your class Object:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;public function __call($sMethod, $aArgs) {
    if (isset($this-&gt;_aProperties[$sMethod])) {
        $f = $this-&gt;_aProperties[$sMethod];
        $nArgCount = count($aArgs);
        $aArgTokens = array(&#39;$this&#39;);
        for ($i=0; $i&lt;$nArgCount; $i++) {
            $aArgTokens[] = &#39;$aArgs[&#39;.$i.&#39;]&#39;;
        }
        $sArgTokens = implode(&#39;,&#39;, $aArgTokens);
 $sEval = &#39;return $f(&#39;.$sArgTokens.&#39;);&#39;;
 return eval($sEval);
    }
}
&lt;/pre&gt;
Now you can add dynamic methods almost like in JavaScript:

&lt;pre class=&quot;code brush: php&quot;&gt;$oMyObject = new Object();
$oMyObject-&gt;myNewMethod = function($owner, $someparam) { print $someparam; };
$oMyObject-&gt;myNewMethod(&#39;Yay! Javascript-style methods!&#39;);
&lt;/pre&gt;Note the extra &quot;$owner&quot; parameter. It is reserved to use instead of &quot;$this&quot; in this implementation. Closure implementation in php is still not smart enough to accept $this from the scope of the object they are called from.



So, now you are like: &quot;huh? oooh! yeah! ...but...&quot;.

Take a moment to digest it. Breathe.
To answer some questions that may be forming in your mind:
Yes, it does all the things a method should do:

1. As I mentioned, use $owner instead of $this, and it will be provided for you.
   Say if you have a protected or private property $myPrivateProp, you can access it like so:

&lt;pre class=&quot;code brush: php&quot;&gt;$oMyObject-&gt;getPrivateProp = function($owner) { return $owner-&gt;myPrivateProp; };
&lt;/pre&gt;2. Pass by reference is supported if you specify it in both places: definition and call. Like so:

&lt;pre class=&quot;code brush: php&quot;&gt;$ref = 1;
    $oMyObject-&gt;test = function($owner, &amp;$ref) { return $ref = 2; };
    print $ref; // outputs: 1
    print $oMyObject-&gt;test(&amp;$ref);
    print $ref; // outputs: 2
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://dot-php.blogspot.com/feeds/7185784907121727155/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/7750105339598410554/7185784907121727155' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/7185784907121727155'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/7185784907121727155'/><link rel='alternate' type='text/html' href='http://dot-php.blogspot.com/2010/03/dynamically-adding-methods-in-php-base.html' title='Dynamically adding methods in PHP  ::  Base Object :: Part 3'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7750105339598410554.post-5610994563125972208</id><published>2010-03-02T15:07:00.001-08:00</published><updated>2010-03-11T17:22:53.501-08:00</updated><title type='text'>Static Constructor in PHP  ::  Base Object :: Part 1</title><content type='html'>In these series I will show a few neat examples of what is possible with PHP5-5.3. I will not reiterate on the obvious, but try to expose the features that are not widely explored.&lt;br /&gt;
&lt;br /&gt;
Starting from this first article I will be building a base object for our library: class Object, so that every class extending it would inherit all the features we add here.&lt;br /&gt;
&lt;br /&gt;
The first feature is indirectly available to us from PHP5.0.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;INLINE STATIC CONSTRUCTOR&lt;/b&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;class Object {
    public static function construct() {
        $aArgs = func_get_args();
        $nArgCount = count($aArgs);
        $aArgTokens = array(&#39;$this&#39;);
        for ($i=0; $i&lt;$nArgCount; $i++) {
            $aArgTokens[] = &#39;$aArgs[&#39;.$i.&#39;]&#39;;
        }
        $sArgTokens = implode(&#39;,&#39;, $aArgTokens);
        $sEval = &#39;return new &#39;.get_called_class().&#39;(&#39;.$sArgTokens.&#39;);&#39;;
        return eval($sEval);
    }
}
&lt;/pre&gt;
What does it do?
Well, consider this code: 

&lt;pre class=&quot;code brush: php&quot;&gt;$oMyObject = new Object();
    $oMyObject-&gt;myMethod();
&lt;/pre&gt;You can now do:

&lt;pre class=&quot;code brush: php&quot;&gt;Object::construct()-&gt;myMethod();
&lt;/pre&gt;&lt;br /&gt;
Notice, you can still assign the return value to $oMyObject for the future reference if needed.&lt;br /&gt;
&lt;br /&gt;
Stay tuned, more interesting patters coming up.</content><link rel='replies' type='application/atom+xml' href='http://dot-php.blogspot.com/feeds/5610994563125972208/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/7750105339598410554/5610994563125972208' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/5610994563125972208'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/5610994563125972208'/><link rel='alternate' type='text/html' href='http://dot-php.blogspot.com/2010/03/static-constructor-in-php-base-object.html' title='Static Constructor in PHP  ::  Base Object :: Part 1'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7750105339598410554.post-2098625451760449750</id><published>2010-03-02T15:06:00.001-08:00</published><updated>2010-03-11T17:23:04.961-08:00</updated><title type='text'>Dynamically adding properties in PHP  ::  Base Object :: Part 2</title><content type='html'>I promised in my previous article that I will not talk about the obvious in PHP. However, this one deserves mentioning, since we will be building on top of it as we go along.&lt;br /&gt;
&lt;br /&gt;
Add this to our class Object that we have started in the Part 1 of this article.&lt;br /&gt;
All it does - it makes our object property-extensible.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;protected $_aProperties = array();
...
public function __get($sProperty) {
    return isset($this-&gt;_aProperties[$sProperty]) 
        ? $this-&gt;_aProperties[$sProperty] 
        : null;
}
public function __set($sProperty, $mValue) {
    $this-&gt;_aProperties[$sProperty] = $mValue;
    return $mValue; 
}
&lt;/pre&gt;&lt;br /&gt;
Now you can set properties dynamically, like so:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code brush: php&quot;&gt;$oMyObject-&gt;non_existing_property = 6;
print $oMyObject-&gt;non_existing_property; // outputs: 6
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://dot-php.blogspot.com/feeds/2098625451760449750/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/7750105339598410554/2098625451760449750' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/2098625451760449750'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7750105339598410554/posts/default/2098625451760449750'/><link rel='alternate' type='text/html' href='http://dot-php.blogspot.com/2010/03/dynamically-adding-properties-in-php.html' title='Dynamically adding properties in PHP  ::  Base Object :: Part 2'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry></feed>