<?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>Compiled Thoughts by John Ciacia &#187; PHP</title>
	<atom:link href="http://www.johnciacia.com/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.johnciacia.com</link>
	<description>Science, Technology, and Beyond</description>
	<lastBuildDate>Fri, 06 Jan 2012 15:46:22 +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>Object and Array Casting</title>
		<link>http://www.johnciacia.com/2011/11/29/object-and-array-casting/</link>
		<comments>http://www.johnciacia.com/2011/11/29/object-and-array-casting/#comments</comments>
		<pubDate>Tue, 29 Nov 2011 19:24:16 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[cast]]></category>
		<category><![CDATA[object]]></category>

		<guid isPermaLink="false">http://www.johnciacia.com/?p=1355</guid>
		<description><![CDATA[A few days ago, I posted about some interesting behavior when casting arrays to objects. I would like to take a look at some other interesting behavior. Lets start be creating a basic class Test with three properties each with a different visibility. [code]class Test { private $foo; protected $bar; public $bat; public function __construct() [...]]]></description>
			<content:encoded><![CDATA[<p>A few days ago, I posted about some interesting behavior when casting <a href="http://www.johnciacia.com/2011/11/08/curly-braces-for-invalid-class-property-name/">arrays to objects</a>. I would like to take a look at some other interesting behavior. Lets start be creating a basic class <strong>Test</strong> with three properties each with a different visibility.</p>
<p>[code]class Test {<br />
  private $foo;<br />
  protected $bar;<br />
  public $bat;</p>
<p>  public function __construct() {<br />
    $this-&gt;foo = &quot;lorem&quot;;<br />
    $this-&gt;bar = &quot;dolor&quot;;<br />
    $this-&gt;bat = &quot;amit&quot;;<br />
  }<br />
}[/code]</p>
<p>Now create a new instance of the class and cast it to an array.<br />
[code]$test = new Test();<br />
print_r((array)$test);[/code]<br />
The result is as follows:<br />
[code]Array<br />
(<br />
    [Testfoo] =&gt; lorem<br />
    [*bar] =&gt; dolor<br />
    [bat] =&gt; amit<br />
)[/code]<br />
On the surface it appears as if the private property had the class name prepended and the and the protected property had an astrick prepended. Now what happens if we cast this array back to an object?<br />
[code]$test_object = new Test();<br />
$test_array = (array)$test_object;<br />
var_dump((object)$test_array);[/code]</p>
<p>Results in:<br />
[code]object(stdClass)#2 (3) {<br />
  [&quot;foo&quot;:&quot;Test&quot;:private]=&gt;<br />
  string(5) &quot;lorem&quot;<br />
  [&quot;bar&quot;:protected]=&gt;<br />
  string(5) &quot;dolor&quot;<br />
  [&quot;bat&quot;]=&gt;<br />
  string(4) &quot;amit&quot;<br />
}[/code]</p>
<p>How did PHP know the <strong>Testfoo</strong> key and the <strong>*bar</strong> key were private and protected? After all, doing the following does not work:<br />
[code]$test_array = array(&quot;Testfoo&quot; =&gt; &quot;lorem&quot;, &quot;*bar&quot; =&gt; &quot;dolor&quot;, &quot;bat&quot; =&gt; &quot;amit&quot;);<br />
var_dump((object)$test_array);[/code]</p>
<p>It turns out, PHP stores meta information with the keys in the form of null bytes. Thus<br />
[code]$test_array = array(<br />
  &quot;\x00Test\x00foo&quot; =&gt; &quot;lorem&quot;,<br />
  &quot;\x00*\x00bar&quot; =&gt; &quot;dolor&quot;,<br />
  &quot;bat&quot; =&gt; &quot;amit&quot;<br />
  );<br />
var_dump((object)$test_array);[/code]<br />
Results in the object we expect.<br />
[code]object(stdClass)#2 (3) {<br />
  [&quot;foo&quot;:&quot;Test&quot;:private]=&gt;<br />
  string(5) &quot;lorem&quot;<br />
  [&quot;bar&quot;:protected]=&gt;<br />
  string(5) &quot;dolor&quot;<br />
  [&quot;bat&quot;]=&gt;<br />
  string(4) &quot;amit&quot;<br />
}[/code]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnciacia.com/2011/11/29/object-and-array-casting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Curly Braces for Class Property Names</title>
		<link>http://www.johnciacia.com/2011/11/08/curly-braces-for-invalid-class-property-name/</link>
		<comments>http://www.johnciacia.com/2011/11/08/curly-braces-for-invalid-class-property-name/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 15:22:09 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.johnciacia.com/?p=1336</guid>
		<description><![CDATA[I ran into an interesting situation the other day where I was parsing an RSS into a SimpleXML object. I cannot recall the exact situation but I will replicate it below. Suppose you have an associative array with a key that that is not a valid variable name. This can happen if the key begins [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into an interesting situation the other day where I was parsing an RSS into a SimpleXML object. I cannot recall the exact situation but I will replicate it below. Suppose you have an associative array with a key that that is not a valid variable name. This can happen if the key begins with a number or if the key has spaces it in. For example:</p>
<p>[code]<br />
$a['1st_key'] = &quot;first_key&quot;;<br />
$a['k e y'] = &quot;value&quot;;<br />
[/code]</p>
<p>Now lets say, for whatever reason, we cast this array to an object:</p>
<p>[code]<br />
$o = (object)$a;<br />
[/code]</p>
<p>This will convert all the array keys into the objects properties. But, how do we access them? Both <code>$o->k e y</code> and <code>$o->1st_key</code> are obvious syntax errors. As a solution, you can use curly braces.</p>
<p>[code]<br />
echo $o-&gt;{'1st_key'};<br />
echo $o-&gt;{'k e y'};<br />
[/code]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnciacia.com/2011/11/08/curly-braces-for-invalid-class-property-name/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Get Trending Topics from Twitter</title>
		<link>http://www.johnciacia.com/2011/07/03/get-trending-topics-from-twitter/</link>
		<comments>http://www.johnciacia.com/2011/07/03/get-trending-topics-from-twitter/#comments</comments>
		<pubDate>Mon, 04 Jul 2011 04:29:41 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Snippets]]></category>

		<guid isPermaLink="false">http://www.johnciacia.com/?p=1281</guid>
		<description><![CDATA[I recently had the need to get the trending topics on Twitter, and discovered it was really easy. Below is the code: [code]$url = &#34;http://api.twitter.com/1/trends/1.json&#34;; $data = json_decode(file_get_contents($url)); print_r($data); [/code]]]></description>
			<content:encoded><![CDATA[<p>I recently had the need to get the trending topics on Twitter, and discovered it was really easy. Below is the code:</p>
<p>[code]$url = &quot;http://api.twitter.com/1/trends/1.json&quot;;<br />
$data = json_decode(file_get_contents($url));<br />
print_r($data);<br />
[/code]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnciacia.com/2011/07/03/get-trending-topics-from-twitter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP is a bad programming language</title>
		<link>http://www.johnciacia.com/2011/05/20/php-is-a-bad-programming-language/</link>
		<comments>http://www.johnciacia.com/2011/05/20/php-is-a-bad-programming-language/#comments</comments>
		<pubDate>Fri, 20 May 2011 23:06:48 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[Crappy Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.johnciacia.com/?p=1015</guid>
		<description><![CDATA[Recently I was having a discussion with a friend who insisted PHP is a bad programming language. His main argument was that PHP makes it easy for crappy programmers to write crappy code, therefore PHP is a bad programming language. I will admit, crappy programmers can write crappy code in PHP &#8211; but that does [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I was having a discussion with a friend who insisted PHP is a <strong>bad</strong> programming language. His main argument was that <em>PHP makes it easy for crappy programmers to write crappy code</em>, therefore PHP is a bad programming language. I will admit, crappy programmers can write crappy code in PHP &#8211; but that does not make it a valid metric for comparing languages. In fact, crappy programmers can write crappy code in ANY language.</p>
<p>Lets take a look at C &#8211; an old and well respected programming language. While it is indeed very fast, the amount of built in functions are minimal. In PHP, if I want to sort an array, I can simply call the <code>sort()</code> function and it will use a fairly optimal and non-intuitive sorting algorithm, quick sort which runs in <em>O(n*log n)</em> time. Where as a crappy C programmer might write a more intuitive sorting algorithm, selection sort, which yields a <em>O(n<sup>2</sup>)</em> time. Therefore C is a crappy programming language because the programmer wrote a crappier algorithm. Or is it that C is a better programming language because it makes it <strong>hard</strong> for crappy programmers to write bad code?</p>
<p>What about automobiles? Cars make it really easy for crappy drivers to get into accidents. Thus driving an automobile is a bad mode of transportation.</p>
<p>What it really comes down to, is that people use the best tool for the job.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnciacia.com/2011/05/20/php-is-a-bad-programming-language/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Array vs SplFixedArray</title>
		<link>http://www.johnciacia.com/2011/02/01/array-vs-splfixedarray/</link>
		<comments>http://www.johnciacia.com/2011/02/01/array-vs-splfixedarray/#comments</comments>
		<pubDate>Tue, 01 Feb 2011 06:06:14 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[spl]]></category>
		<category><![CDATA[splfixedarray]]></category>
		<category><![CDATA[standard php library]]></category>

		<guid isPermaLink="false">http://www.johnciacia.com/?p=814</guid>
		<description><![CDATA[PHP offers eight primitive types to the user. One of them being an array. An interesting aspect of PHP arrays is that they are allocated dynamically. Thus, the following code is perfectly acceptable: [code lang="php"]]]></description>
			<content:encoded><![CDATA[<p>PHP offers eight primitive types to the user. One of them being an array. An interesting aspect of PHP arrays is that they are allocated dynamically. Thus, the following code is perfectly acceptable:</p>
<p>[code lang="php"]<?php<br />
$arr = array(1, 2, 3, 4);<br />
$arr[50] = 50;<br />
[/code]</p>
<p>
The first line set the first four indexes to one through four respectively. This creates an array of size four. The second line sets index fifty to the value fifty augmenting the array size by one. Indexes five through forty nine do not exist, and attempting to access a non existing element will only raise an E_Notice level error message. The dynamic allocation of arrays allows programmers to ignore out of bounds exceptions, segmentation faults, and hours of debugging, but it also leads to a slower write time because the memory locations needed to hold the new data is not already allocated.</p>
<p>The Standard PHP Library offers a <strong><a href="http://www.php.net/manual/en/class.splfixedarray.php">SplFixedArray</a></strong> object that pre-allocates the necessary memory thereby solving the issue of slower write times.</p>
<p>[code lang="php"]<?php</p>
<p>$array = new SplFixedArray(5);<br />
print_r($array);[/code]<br />
Which results in (a pre-allocated array)</p>
<blockquote><p>SplFixedArray Object<br />
(<br />
[0] =&gt;<br />
[1] =&gt;<br />
[2] =&gt;<br />
[3] =&gt;<br />
[4] =&gt;<br />
)</p></blockquote>
<h2>Creation Time</h2>
<p>To verify this, I ran a test that writes data to an array and an SplFixedArray and measures the time for different amounts of elements.</p>
<p>[code lang="php"]<?php</p>
<p>for($size = 1000; $size < 100000; $size *= 2) {<br />
  $f = $size;<br />
  for($t = microtime(true), $a = array(), $i = 0; $i < $size; $i++) {<br />
    $a[$i] = NULL;<br />
  }<br />
  $f .= "," . (microtime(true) - $t) . ",";</p>
<p>  for($t = microtime(true), $a = new SplFixedArray($size), $i = 0; $i < $size; $i++) {<br />
    $a[$i] = NULL;<br />
  }<br />
  $f .= (microtime(true) - $t) . "\n";<br />
  file_put_contents("./data.csv", $f, FILE_APPEND);<br />
}[/code]</p>
<div align="left"><a href="http://www.johnciacia.com/wp-content/uploads/2011/01/1.png"><img class="size-full wp-image-818 aligncenter" title="1" src="http://www.johnciacia.com/wp-content/uploads/2011/01/1.png" alt="" width="540" height="335" /></a></div>
<h2>Write Time</h2>
<p>It is clear that the SplFixedArray has faster a write time. However, there is a significant overhead when an object is created. To test this, I ran the same test but each time I created a new data structure. From the plot, we can see that creating an array has minimal overhead, whereas creating a new SplFixedArray object and allocating the memory takes a significant more amount of time.</p>
<p>[code lang="php"]<?php</p>
<p>$elements = 20;</p>
<p>for($size = 1000; $size &lt; 100000; $size *= 2) {<br />
  $f = $size;<br />
  for($t = microtime(true), $i = 0; $i < $size; $i++) {<br />
    for($j = 0,$a = array(); $j < $elements; $j++ ) {<br />
      $a[$i] = NULL;<br />
    }<br />
  }<br />
  $f .= "," . (microtime(true) - $t) . ",";</p>
<p>  for($t = microtime(true), $i = 0; $i &lt; $size; $i++) {<br />
    for($j = 0, $a = new SplFixedArray($elements); $j < $elements; $j++) {<br />
      $a[$j] = NULL;<br />
    }<br />
  }<br />
  $f .= (microtime(true) - $t) . "\n";     file_put_contents("./data.csv", $f, FILE_APPEND);<br />
}<br />
[/code]</p>
<div align="left"><a href="http://www.johnciacia.com/wp-content/uploads/2011/01/2.png"><img class="alignnone size-full wp-image-820" title="2" src="http://www.johnciacia.com/wp-content/uploads/2011/01/2.png" alt="" width="540" height="336" /></a></div>
<h2>Memory Footprint</h2>
<p>Lastly I wanted to see how the memory usage differs between each data structure.</p>
<p>[code lang="php"]<?php</p>
<p>for($size = 1000; $size < 100000; $size *= 2) {</p>
<p>  $f = $size . ",";</p>
<p>  $t = memory_get_usage();<br />
  for($a = array(), $i = 0; $i < $size; $i++) {<br />
    $a[$i] = NULL;<br />
  }</p>
<p>  $f .= (memory_get_usage() - $t) . ",";</p>
<p>  $t = memory_get_usage();<br />
  for($a = new SplFixedArray($size), $i = 0; $i < $size; $i++) {<br />
    $a[$i] = NULL;<br />
  }</p>
<p>  $f .= ($t - memory_get_usage()) . "\n";</p>
<p>  file_put_contents("./data.csv", $f, FILE_APPEND);<br />
}</p>
<p>[/code]</p>
<div align="left"><a href="http://www.johnciacia.com/wp-content/uploads/2011/01/3.png"><img class="alignnone size-full wp-image-821" title="3" src="http://www.johnciacia.com/wp-content/uploads/2011/01/3.png" alt="" width="540" height="336" /></a></div>
<h2>Conclusion</h2>
<p>The conclusion is one typical of Computer Science, trade-offs. If you are in an environment where you will need a few arrays with predetermined sizes, the SplFixedArray is the best choice. However, if you will be creating numerous arrays, or the size is unknown, then it is probably better to use the native PHP array.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnciacia.com/2011/02/01/array-vs-splfixedarray/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Coding on the Cloud</title>
		<link>http://www.johnciacia.com/2011/01/12/coding-on-the-cloud/</link>
		<comments>http://www.johnciacia.com/2011/01/12/coding-on-the-cloud/#comments</comments>
		<pubDate>Thu, 13 Jan 2011 00:29:42 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[ChromeOS]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Software Review]]></category>
		<category><![CDATA[chromeos]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[clound9ide]]></category>
		<category><![CDATA[coding on the cloud]]></category>
		<category><![CDATA[cr48]]></category>
		<category><![CDATA[programming on the cloud]]></category>

		<guid isPermaLink="false">http://www.johnciacia.com/?p=791</guid>
		<description><![CDATA[A couple weeks ago I wrote about my experience using the Cr-48 for a week. The conclusion was that the Cr-48 was not ready for John the programmer, but could potentially be the main platform for John the student. This wasn&#8217;t because of ChromeOS, but it was due to the lack of third party software [...]]]></description>
			<content:encoded><![CDATA[<p>A couple weeks ago I wrote about my experience using the <a href="http://www.johnciacia.com/2010/12/26/a-week-with-the-cr-48">Cr-48 for a week</a>. The conclusion was that the Cr-48 was not ready for John the programmer, but could potentially be the main platform for John the student. This wasn&#8217;t because of ChromeOS, but it was due to the lack of third party software for developers, namely an integrated development environment. In my search for a cloud IDE I stumbled across <a href="https://mozillalabs.com/skywriter/">Mozilla Skywriter</a> (formally known as Bespin), <a href="http://kodingen.com/">Kodingen</a>, and <a href="http://www.cloud9ide.com/">Cloud9IDE</a>. Although Kodingen seems to be the most advanced, its not opensource. Skywriter is pretty freaking awesome, and I am super excited that <a href="http://cloud9ide.posterous.com/31591230">Skywriter and Cloud9IDE</a> have teamed up to bring coding to the cloud.</p>
<p>Earlier today <a href="http://twitter.com/#!/Cloud9IDE">@cloud9ide</a> announced a closed beta, with Cr-48 users having preference. I immediately took advantage of the opportunity and signed up. An hour later, my account was approved and I was coding on the cloud.</p>
<p>The layout looks like a typical IDE, it offers syntax highlight for JavaScript, CoffeeScript, CSS, (X)HTML, XML, Python, and PHP. It comes bundled with several different themes, a built in JavaScript debugger, a command line interface, and full support for git. It also appears to work with <a href="http://nodejs.org/">node.js</a>, a technology I have yet to fully explore.</p>
<p>The motto is &#8220;A JavaScript IDE for JavaScripters by JavaScripters,&#8221; which is great, but I&#8217;m PHPer. I would love to see support for pushing files to <strong>my</strong> server/private cloud using ftp/sftp rather than my public GitHub repository.</p>
<p>This project looks very promising, and I look forward to watching the continual development of Cloud9IDE. Keep up the good work guys.</p>
<div id="gallery"><a href="http://www.johnciacia.com/wp-content/uploads/2011/01/screenshot-20110112-191530.png"><img src="http://www.johnciacia.com/wp-content/uploads/2011/01/screenshot-20110112-191530-300x187.png" alt="" title="screenshot-20110112-191530" width="300" height="187" class="alignnone size-medium wp-image-795" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://www.johnciacia.com/2011/01/12/coding-on-the-cloud/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Crappy Code: date and mktime</title>
		<link>http://www.johnciacia.com/2011/01/03/crappy-code-date-and-mktime/</link>
		<comments>http://www.johnciacia.com/2011/01/03/crappy-code-date-and-mktime/#comments</comments>
		<pubDate>Mon, 03 Jan 2011 05:44:29 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[Crappy Code]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[crappy code]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[mktime]]></category>

		<guid isPermaLink="false">http://www.johnciacia.com/?p=755</guid>
		<description><![CDATA[Occasionally (when creating forms) I will need to create a menu that lists the months. I normally use a predefined array and loop through it echoing out the month. From my experience, this is the best method since everything is defined in a single location that has a constant lookup time. [code lang="PHP"]]]></description>
			<content:encoded><![CDATA[<p>Occasionally (when creating forms) I will need to create a menu that lists the months. I normally use a predefined array and loop through it echoing out the month. From my experience, this is the best method since everything is defined in a single location that has a constant lookup time.</p>
<p>[code lang="PHP"]<br />
<select>
<?php<br />
$months = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");<br />
for($i = 0; $i < 12; $i++) {<br />
    echo "<br />
<option value='$i'>$months[$i]</option>
<p>";<br />
}<br />
?><br />
</select>
<p>[/code]</p>
<p>Recently, I was asked to help debug the following code:<br />
[code lang="PHP"]<br />
<select>
<?php<br />
for($i = 0; $i < 12; $i++) {<br />
    echo "<br />
<option value='$i'>" . date("F", mktime(0, 0, 0, $i)) . "</option>
<p>";<br />
}<br />
?><br />
</select>
<p>[/code]</p>
<p>After I flamed this guy for making 24 unnecessary function calls, I noted that <em>arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.</em> Thus when this function ran on the 31st of the month, mktime&#8217;s 5th argument was 31 which causes an error in the following instance <em>mktime(0, 0, 0, 2, 31)</em> (because February does not have 31 days). The solution was to manually set the 5th parameter to 1.</p>
<p>[code lang="PHP"]<br />
<select>
<?php<br />
for($i = 0; $i < 12; $i++) {<br />
    echo "<br />
<option value='$i'>" . date("F", mktime(0, 0, 0, $i, 1)) . "</option>
<p>";<br />
}<br />
?><br />
</select>
<p>[/code]</p>
<p>This will generate the correct months, but still does not fix the problem of making 24 unnecessary function calls.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnciacia.com/2011/01/03/crappy-code-date-and-mktime/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>No require with autoload</title>
		<link>http://www.johnciacia.com/2011/01/02/no-require-with-autoload/</link>
		<comments>http://www.johnciacia.com/2011/01/02/no-require-with-autoload/#comments</comments>
		<pubDate>Sun, 02 Jan 2011 21:57:27 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[autoload]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[namespace]]></category>
		<category><![CDATA[php5]]></category>
		<category><![CDATA[php6]]></category>
		<category><![CDATA[require]]></category>

		<guid isPermaLink="false">http://www.johnciacia.com/?p=734</guid>
		<description><![CDATA[If you have ever worked with a PHP framework you probably have noticed some features that allow you to develop code more rapidly. In this blog, I am going to address autoloading. Traditionally, in object oriented PHP, we create a new source file for each class. If we want to create an object of a [...]]]></description>
			<content:encoded><![CDATA[<p>If you have ever worked with a PHP framework you probably have noticed some features that allow you to develop code more rapidly. In this blog, I am going to address autoloading.</p>
<p>Traditionally, in object oriented PHP, we create a new source file for each class. If we want to create an object of a class, we have to include the php file using require_once (or using a similar function). If we do not include the source file, we will be issued a fatal error.</p>
<p>
<pre><strong>Fatal error</strong>: Class 'User' not found in ...</pre>
</p>
<p>Lets say we have a User class defined as follows in a User.php file</p>
<p>[code lang="PHP"]<?php</p>
<p>class User {<br />
    function __construct() {<br />
        echo "Hello, World!";<br />
    }<br />
}<br />
?>[/code]</p>
<p>If we want to create a new User object we would include user.php and use the new keyword to instantiate the class.</p>
<p>[code lang="PHP"]<?php<br />
require_once('user.php');<br />
$user = new User();[/code]</p>
<p>This is method reasonable for a small number of classes. However, large frameworks can span hundreds of classes, and having to write require_once for each class becomes a huge annoyance. PHP5 introduced an autoload <a href="http://php.net/manual/en/language.oop5.magic.php">magic method</a> which is automatically called if the class source file cannot be found. The __autoload function takes a single parameter - the class being instantiated. If our class name corresponds to its file name we can do something as simple as:</p>
<p>[code lang="PHP"]<?php<br />
function __autoload($class) {<br />
    require_once($class . ".php");<br />
}[/code]</p>
<p>Now, each time you instantiate a class, the autoload function will be automatically ran and it will automagically require your class. This is great, however all classes have to be in the same directory as the callee, and any decent framework uses a class hierarchy and spreads classes out into different directories. When I was writing my framework a few years ago, I stumbled upon a pretty awesome use of the autoload function. I think the idea was borrowed from the Zend framework. In a nutshell, the class names would correspond to their location on the file system. For example, the Zend framework has a class named Zend_Controller_Action_HelperBroker, and the class path Zend/Controller/Action/HelperBroker.php. What does this mean? With some additional code in our autoload function, we can convert the class name into its respective path allowing use to create a class hierarchy on our file system.</p>
<p>[code lang="PHP"]<?php<br />
function __autoload($class) {<br />
    $file = str_replace("_", "/", $class);<br />
    require_once($file . ".php");<br />
}[/code]</p>
<p>Now, with the onset of PHP5.3 and the introduction of namespaces, this method has been kind of depreciated for a more pragmatic method. Instead of naming our classes with really long names that correspond to their path, we can use a namespace instead. Thus our autoload function would look like:</p>
<p>[code lang="PHP"]<?php<br />
function __autoload($class) {<br />
    $file = str_replace("\\", "/", $class);<br />
    require_once($file . ".php");<br />
}[/code]</p>
<p>In my next blog, I will talk more about namespaces and give a better demo on how this is used.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnciacia.com/2011/01/02/no-require-with-autoload/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Error Handling</title>
		<link>http://www.johnciacia.com/2010/12/27/php-error-handling/</link>
		<comments>http://www.johnciacia.com/2010/12/27/php-error-handling/#comments</comments>
		<pubDate>Tue, 28 Dec 2010 02:31:32 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.johnciacia.com/?p=727</guid>
		<description><![CDATA[Over this past summer, one of my tasks was to integrate active directory with a ticket management software for a local school district. This software was probably written ten years ago when PHP 4 was defacto, using superglobals to access POST/GET data was not the norm, and before the rise of the MVC architecture on [...]]]></description>
			<content:encoded><![CDATA[<p>Over this past summer, one of my tasks was to integrate active directory with a ticket management software for a local school district. This software was probably written ten years ago when PHP 4 was defacto, using superglobals to access POST/GET data was not the norm, and before the rise of the MVC architecture on the web. Since the code was so tightly coupled, rewriting the authentication system meant rewriting code in almost every file. I probably would have threw out the entire code base and started fresh, but the budget was tight and I wanted experience working with someone else&#8221;s code other than my own. For the most part, the code has been successfully deployed and over the past few months, a few thousand tickets have been submitted. However, occasionally users complain they get errors when using the system (and of course never provide any useful feedback as to how to replicate the error). Sure, I could turn error reporting off, but the errors would go unnoticed and never get fixed. I did the opposite. I turned error reporting on as high as it would go and created a custom error handler that would email me diagnostic information each time an error, warning, or notice happened. For the first few days my inbox was flooded with messages from undefined variables (lesson learned), but the messages have fizzled down to almost nothing. Below is the error handler is use:</p>
<p>[code lang="php"]<?php<br />
ini_set('display_errors',1);<br />
error_reporting(E_ALL &#038; E_NOTICE);</p>
<p>function error_handler($errno, $errstr, $errfile, $errline)<br />
{<br />
    if (!(error_reporting() &#038; $errno)) {<br />
        return;<br />
    }<br />
    ob_start();<br />
    echo $errno . " " . $errstr . "\n\n";<br />
    print_r($_SESSION);<br />
    echo "\n";<br />
    print_r($_GET);<br />
    echo "\n";<br />
    print_r($_POST);<br />
    echo "\n";<br />
    print_r($_SERVER);<br />
    echo "\n";<br />
    debug_print_backtrace();<br />
    $body = ob_get_contents();<br />
    ob_end_clean();<br />
    mail('john@example.com', 'Software Error', $body);<br />
    return false;<br />
}<br />
$old = set_error_handler("error_handler");<br />
?>[/code]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnciacia.com/2010/12/27/php-error-handling/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Short-Circuit Evaluation in PHP</title>
		<link>http://www.johnciacia.com/2010/10/18/short-circuit-evaluation-in-php/</link>
		<comments>http://www.johnciacia.com/2010/10/18/short-circuit-evaluation-in-php/#comments</comments>
		<pubDate>Tue, 19 Oct 2010 01:29:32 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.johnciacia.com/?p=666</guid>
		<description><![CDATA[A few weeks ago an excellent question was asked on CodeCall &#8211; Programming Forum regarding the PHP OR operator. We typically think of it as a logical operator. [code lang="php"]]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago an excellent question was asked on <a href="http://forum.codecall.net/php-forum/31507-php-operator-language-construct-what.html">CodeCall &#8211; Programming Forum</a> regarding the PHP <strong>OR</strong> operator. We typically think of it as a <a href="http://php.net/manual/en/language.operators.logical.php">logical operator</a>. </p>
<p>[code lang="php"]<?php<br />
$a or $b;[/code]<br />
Logically this means <strong>TRUE</strong> if either $a or $b is <strong>TRUE</strong>. Normally, we assume PHP will replace the left most operand ($a) with its boolean value, then replace the right most operand ($b) to with its boolean value, and finally evaluate the logical expression using the given operator. However, consider the use of the OR operator in the following context:<br />
[code lang="php"]<?php<br />
$result = mysql_query("SELECT * FROM `table`") or die(mysql_error());[/code]<br />
We do this quite often, and we interpret it to mean "<em>if</em> the mysql query fails, <em>then </em>halt operation and output an error message." That is, we interpret it as a <em>conditional expression</em>, and NOT as a <em>logical expression</em>. This is because in PHP uses <strong>short-circuit evaluation</strong> with the following operators
<pre>&#038;&#038;, and, ||, or</pre>
<p></p>
<p>
With short-circuit evaluation, the second argument is only evaluated if and only if the first argument does not suffice to determine the value of the expression. Thus, when the query is successful, the die() expression is never executed.</p>
<p>Note: For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. PHP will assumes anything that is not strictly false to be true. Thus a resource is evaluated to be <em>true</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnciacia.com/2010/10/18/short-circuit-evaluation-in-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced

Served from: www.johnciacia.com @ 2012-02-05 10:55:39 -->
