<?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>scriptNode &#187; Intermediate</title>
	<atom:link href="http://scriptnode.com/category/intermediate/feed/" rel="self" type="application/rss+xml" />
	<link>http://scriptnode.com</link>
	<description>Tips and tricks for web developers.</description>
	<lastBuildDate>Tue, 01 Sep 2009 18:46:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Common PHP Equivalents in JavaScript</title>
		<link>http://scriptnode.com/article/common-php-equivalents-in-javascript/</link>
		<comments>http://scriptnode.com/article/common-php-equivalents-in-javascript/#comments</comments>
		<pubDate>Sat, 03 Jan 2009 09:04:45 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=245</guid>
		<description><![CDATA[
It&#8217;s pretty widely known in the web development industry that server-side scripting is important, and PHP is an extremely common choice. Indeed, for many programmers it&#8217;s even  their first language. It&#8217;s quite common for web devs to begin on the server, then later require some client-side interaction, at which point they must turn to [...]]]></description>
			<content:encoded><![CDATA[<p>
It&#8217;s pretty widely known in the web development industry that server-side scripting is important, and <a href="http://us3.php.net/" title="PHP Hypertext Preprocessor">PHP</a> is an extremely common choice. Indeed, for many programmers <a href="http://reidburke.com/2008/10/05/when-php-is-your-first-language/">it&#8217;s even  their first language</a>. It&#8217;s quite common for web devs to begin on the server, then later require some client-side interaction, at which point they must turn to <a href="/tag/javascript/">JavaScript</a>.
</p>
<p>
I often see questions similar to, &#8220;I&#8217;ve got these few lines of PHP code, how would I do this in JavaScript?&#8221; I&#8217;ve actually <a href="/article/javascript-print_r-or-var_dump-equivalent/">already answered</a> a question like this, but I kept getting more questions, so I thought I&#8217;d cover many at once:
</p>
<ul>
<li><a href="#array-push">Pushing to an array</a></li>
<li><a href="#die"><code>die()</code> or <code>exit</code></a></li>
<li><a href="#include"><code>include</code> or <code>require</code></a></li>
<li><a href="#redirection">Redirection</a></li>
<li><a href="#static-classes">Static classes</a></li>
<li><a href="#strings">String manipulation</a></li>
</ul>
<h3 id="array-push">Pushing to an array</h3>
<p>
Pushing a new value to the end of an array is a common, trivial task. Here&#8217;s some PHP to accomplish this:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$my_array = array();<br />
$my_array[] = &#8216;a&#8217;;<br />
array_push($my_array, &#8216;b&#8217;);<br />
</textarea></p>
<p>
Also note this quick pointer from php.net&#8217;s <a href="http://us3.php.net/manual/en/function.array-push.php"><code>array_push()</code> documentation</a>:
</p>
<blockquote><p>If you use <code>array_push()</code> to add one element to the array it&#8217;s better to use <code>$array[] =</code> because in that way there is no overhead of calling a function.</p>
</blockquote>
<p>
This isn&#8217;t the case in JavaScript. The native <code>Array.push</code> method is most optimal:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var myArray = [];<br />
myArray.push(&#8217;a'); // This is the way to go<br />
myArray[myArray.length] = &#8216;b&#8217;; // This method is possible but bad<br />
</textarea></p>
<h3 id="die"><code>die()</code> or <code>exit</code></h3>
<p>
There has been much confusion regarding what JavaScript is and how it works in the browser. When looking for an equivalent to <code>exit</code>, one probably doesn&#8217;t understand that client-side JavaScript is a behavioral language that&#8217;s intended to react to events. In PHP, a script executes, stopping only when told to do so, and then it&#8217;s done. JavaScript lives and breathes on the page, reacting to the mouse being moved, keys being pressed and even time changing.
</p>
<p>
So it&#8217;s important to understand why this is not a fair equivalent, and that even asking for one shows a misunderstanding. That said, a bit of procedural JavaScript can be exited by using an anonymous function. Here&#8217;s some example PHP and then similar code in JavaScript:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
if ($next_action == &#8216;exit&#8217;) {<br />
	exit;<br />
}</p>
<p>echo &#8216;Made it here!&#8217;;<br />
</textarea></p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
(function() {</p>
<p>	if (nextAction == &#8216;exit&#8217;) {<br />
		return;<br />
	}</p>
<p>	alert(&#8217;Made it here!&#8217;);</p>
<p>})();<br />
</textarea></p>
<p>
While the language behavior is not one-to-one, taking advantage of JavaScript&#8217;s closure already has advantages, among them being able to easily exit a function via <code>return</code>.
</p>
<h3 id="include"><code>include</code> or <code>require</code></h3>
<p>
There have been some arguments about this equivalence in JavaScript. Just like the previous example, this equivalence is not one-to-one and should be thought about in very different terms. That said, here is a quick example of including a PHP file within a PHP script:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
// Nothing to it, just include the file:<br />
include(&#8217;my_file.php&#8217;);</p>
<p>// This code will only execute after my_file.php has been included:<br />
echo &#8216;File included!&#8217;;<br />
</textarea></p>
<p>
To include an external script in JavaScript, writing a method or including a library is definitely best. <a href="/article/dynamically-load-css-and-js-files/">I wrote about this once</a>, but there are libraries such as <a href="http://developer.yahoo.com/yui/" title="Yahoo! User Interface library">YUI</a> that have <a href="http://developer.yahoo.com/yui/get/">better support with more options</a>. Here&#8217;s what this would look like using YUI:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Call YUI&#8217;s method<br />
var objTransaction = YAHOO.util.Get.script(&#8221;http://example.com/my_file.js&#8221;, {<br />
	// This function will only fire after my-file.js has been included:<br />
	onSuccess : function() {<br />
		alert(&#8221;File included!&#8221;);<br />
	}<br />
});<br />
</textarea></p>
<h3 id="redirection">Redirection</h3>
<p>
This one is easy and straightforward. A redirect is accomplished with <a href="http://us3.php.net/manual/en/function.header.php">PHP&#8217;s <code>header()</code> function</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
header(&#8217;Location: http://example.com&#8217;);<br />
exit; // Not necessary but a good practice<br />
</textarea></p>
<p>
Also very simple in JavaScript:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
location.href = &#8216;http://example.com&#8217;;<br />
</textarea></p>
<h3 id="static-classes">Static classes</h3>
<p>
In PHP, it&#8217;s a pretty common programming pattern to use a static class for encapsulation, sort of namespacing some methods and properties. Here&#8217;s an example:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
class Tools {</p>
<p>    public static function check_stuff() {<br />
        return true;<br />
    }</p>
<p>}</p>
<p>echo Tools::check_stuff();<br />
</textarea></p>
<p>
For this JavaScript equivalence, it probably makes the most sense to use an object literal:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
Tools = {<br />
	checkStuff : function() {<br />
		return true;<br />
	}<br />
};</p>
<p>alert(Tools.checkStuff());<br />
</textarea></p>
<h3 id="strings">String manipulation</h3>
<p>
String manipulation is absolutely mandatory in most applications. Fortunately, it&#8217;s a breeze thanks to <a href="http://us3.php.net/manual/en/ref.strings.php">PHP&#8217;s fantastic string functions</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
// Replace portions within a string<br />
echo str_replace(&#8217;Hey&#8217;, &#8216;Hi&#8217;, &#8216;Hey there&#8217;); // outputs &#8220;Hi there&#8221;</p>
<p>// Capitalization<br />
echo strtolower(&#8217;Hey there&#8217;); // outputs &#8220;hey there&#8221;<br />
echo strtoupper(&#8217;Hey there&#8217;); // outputs &#8220;HEY THERE&#8221;</p>
<p>// Get a portion of a string<br />
echo substr(&#8217;Hey there&#8217;, 0, 2); // outputs &#8220;He&#8221;</p>
<p>// Get rid of extraneous whitespace<br />
echo trim(&#8217;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hey there&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8217;); // outputs &#8220;Hey there&#8221;<br />
</textarea></p>
<p>
<a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String" title="Mozilla's String reference">Each of these</a> have perfect equivalents except for <code>trim()</code>, which we need to implement ourselves:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Replace portions within a string<br />
alert(&#8217;Hey there&#8217;.replace(&#8217;Hey&#8217;, &#8216;Hi&#8217;)); // outputs &#8220;Hi there&#8221;</p>
<p>// Capitalization<br />
alert(&#8217;Hey there&#8217;.toLowerCase()); // outputs &#8220;hey there&#8221;<br />
alert(&#8217;Hey there&#8217;.toUpperCase()); // outputs &#8220;HEY THERE&#8221;</p>
<p>// Get a portion of a string<br />
alert(&#8217;Hey there&#8217;.substr(0, 2)); // outputs &#8220;He&#8221;</p>
<p>// Get rid of extraneous whitespace<br />
trim = function(txt) {<br />
	return txt.replace(/^\s+|\s+$/g, &#8221;);<br />
};</p>
<p>alert(trim(&#8217;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hey there&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8217;)); // outputs &#8220;Hey there&#8221;</p>
<p></textarea></p>
<p>
Or, we can augment the <code>String</code> global so that strings will have this method natively:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
String.prototype.trim = function() {<br />
	return this.replace(/^\s+|\s+$/g, &#8221;);<br />
};</p>
<p>// Get rid of extraneous whitespace<br />
alert(&#8217;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hey there&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8217;.trim()); // outputs &#8220;Hey there&#8221;<br />
</textarea></p>
<p>
While not all of these equivalents are smooth (or even recommended), it&#8217;s typically helpful when learning a new language to have it compared to a language one is already familiar with. If you can think of any other common PHP tasks that have relatively similar equivalents in JavaScript, please let me know in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/common-php-equivalents-in-javascript/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Multiline Strings in JavaScript</title>
		<link>http://scriptnode.com/article/multiline-strings-in-javascript/</link>
		<comments>http://scriptnode.com/article/multiline-strings-in-javascript/#comments</comments>
		<pubDate>Wed, 22 Oct 2008 00:17:48 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=217</guid>
		<description><![CDATA[
The ability to write multiline strings is a common feature in many languages. It promotes readability and is often much cleaner than the alternatives. Here&#8217;s a typically ugly example of string concatenation in PHP:


$my_string = &#8220;This string\n&#8221;;
$my_string .= &#8220;spans multiple\n&#8221;;
$my_string .= &#8220;lines.\n&#8221;;


Thankfully, PHP has the benefit of heredoc syntax, which makes code like this much [...]]]></description>
			<content:encoded><![CDATA[<p>
The ability to write multiline strings is a common feature in many languages. It promotes readability and is often much cleaner than the alternatives. Here&#8217;s a typically ugly example of string concatenation in <a href="http://us2.php.net/" title="PHP Hypertext Preprocessor">PHP</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$my_string = &#8220;This string\n&#8221;;<br />
$my_string .= &#8220;spans multiple\n&#8221;;<br />
$my_string .= &#8220;lines.\n&#8221;;<br />
</textarea></p>
<p>
Thankfully, PHP has the benefit of <a href="http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc">heredoc syntax</a>, which makes code like this much easier to read, write and maintain:
</p>
<p><textarea class="php" cols="50" id="heredoc-example" name="code" rows="10"><br />
$my_string = &lt;&lt;&lt;MYSTRING<br />
This string<br />
spans multiple<br />
lines.<br />
MYSTRING;<br />
</textarea></p>
<h3>E4X</h3>
<p>
But what about <a href="http://developer.mozilla.org/en/JavaScript">JavaScript</a>? There is no native heredoc support, but there are some other workarounds that can be used. The first I&#8217;ll offer up is <a href="http://en.wikipedia.org/wiki/E4X">ECMAScript for XML (E4X)</a>.
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var myString = &#8221; + &lt;myString&gt;&lt;![CDATA[This string<br />
spans multiple<br />
lines.<br />
]]&gt;&lt;/myString&gt;;<br />
</textarea></p>
<p>
The first line in the above example is a bit confusing. The <acronym title="Extensible Markup Language">XML</acronym> will return an xml object by default, but what we want is a <code>String</code>. We can type the return as a <code>String</code> by concatenating to an empty string (<code>''</code>).
</p>
<p>
Next, an element must be wrapped around the <code>CDATA</code> to trigger the <acronym>XML</acronym> parser. This step is similar to PHP&#8217;s <a href="#heredoc-example">heredoc syntax</a> in that it requires an identical beginning and ending identifier.
</p>
<p>
You can test this yourself <a href="/lab/e4x/">in the lab</a>.<br />
Currently, it looks like only <a href="http://developer.mozilla.org/En/Gecko">Gecko</a> browsers (such as <a href="http://www.mozilla.com/en-US/firefox/">Firefox</a> and <a href="http://caminobrowser.org/">Camino</a>) support E4X. This obviously doesn&#8217;t include <a href="http://browsehappy.com/why/">Internet Explorer</a>, which is (unfortunately) often a large portion of most websites&#8217; user bases. While this workaround is interesting, it&#8217;s definitely not realistic to assume all of your users are using Firefox, <a href="http://xkcd.com/111/">despite its rising popularity</a> (also, it will <a href="http://tr.im/hez">fail to validate</a>).
</p>
<h3>Hidden Element Hack</h3>
<p>
Another workaround I&#8217;ve seen is to place the string inside of an element (often hidden from view) and to read it in via JavaScript. Here&#8217;s an example:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
/* Based on this markup:<br />
&lt;div id=&#8221;multilines&#8221; style=&#8221;display: none;&#8221;&gt;<br />
This string<br />
spans multiple<br />
lines.<br />
&lt;/div&gt;<br />
*/<br />
var myString = document.getElementById(&#8217;multilines&#8217;);<br />
</textarea></p>
<p>
This solution is clever, but definitely a hack job: not very clean, and with a bad <a href="http://www.w3.org/WAI/intro/accessibility.php">accessibility case</a>. The primary issue though is that it doesn&#8217;t completely solve the problem. Markup is needed to interact with the JavaScript code, so to use this solution one couldn&#8217;t maintain a completely independent <code>.js</code> file.
</p>
<h3>Escaping linebreaks</h3>
<p>
Another solution is very simply just to escape line breaks:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
var myString = &#8220;This string\<br />
spans multiple\<br />
lines.&#8221;;<br />
</textarea></p>
<p>
By escaping the linebreak, you&#8217;re free to continue the string on the next line (<em><strong>note:</strong> this doesn&#8217;t include spaces, so if you want to separate words, you&#8217;ll need to begin each new line with a space</em>). This solution is not as attractive as the E4X workaround, but has the benefit of being perfectly cross-browser compatible. Therefore, it looks like it&#8217;s currently the best method available.
</p>
<p>
Do you know of any other workarounds? If so, please let me know in the comments section.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/multiline-strings-in-javascript/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>twittertyper</title>
		<link>http://scriptnode.com/article/twittertyper/</link>
		<comments>http://scriptnode.com/article/twittertyper/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 01:11:51 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[just-for-fun]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[yui]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=157</guid>
		<description><![CDATA[



I unfortunately am not allowed to participate, but in anticipation of Yahoo!&#8217;s Hack Day 2008, I put together a little app I&#8217;ll hopefully be able to port to YAP: twittertyper!


The concept is very simple. twittertyper displays the latest tweet from Twitter. To read the next one, first type out the tweet. The text is highlighted [...]]]></description>
			<content:encoded><![CDATA[<p class="before">
<a href="/lab/twittertyper/"><img alt="twittertyper" src="http://scriptnode.com/lab/twittertyper/logo.png"/></a>
</p>
<p>
I unfortunately am not allowed to participate, but in anticipation of Yahoo!&#8217;s <a href="http://developer.yahoo.net/hackday/">Hack Day 2008</a>, I put together a little app I&#8217;ll hopefully be able to port to <a href="http://developer.yahoo.com/searchmonkey/" title="Yahoo! Application Platform">YAP</a>: <a href="/lab/twittertyper/">twittertyper</a>!
</p>
<p>
The concept is very simple. <strong>twittertyper</strong> displays the latest tweet from <a href="http://twitter.com">Twitter</a>. To read the next one, first <strong>type out the tweet</strong>. The text is highlighted as you go. If you come across a character your keyboard (or operating system) won&#8217;t let you type, just press <code>Esc</code> to move on to the next character.
</p>
<p>
<strong>twittertyper</strong> currently just pulls in from the <a href="http://twitter.com/public_timeline">public timeline</a>; no authentication is supported to pull from <em>your</em> timeline (maybe in a future version). This mini-app is built on <a href="http://developer.yahoo.com/yui/" title="Yahoo! User Interface Library">YUI</a>. Source code (uncompressed) is <a href="/lab/twittertyper/tt.js">free to peruse</a>.
</p>
<p>
<a href="/lab/twittertyper/">Try it out!</a>
</p>
<p>
<em><strong>Note:</strong> If you use Twitter, I&#8217;m sure you&#8217;re used to it being down. Errors happen often, but <strong>twittertyper</strong> attempts to handle them somewhat gracefully. Usually a page reload should suffice.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/twittertyper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google Chrome Benchmarks</title>
		<link>http://scriptnode.com/article/google-chrome-benchmarks/</link>
		<comments>http://scriptnode.com/article/google-chrome-benchmarks/#comments</comments>
		<pubDate>Wed, 03 Sep 2008 07:39:18 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[benchmarks]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=91</guid>
		<description><![CDATA[
So unless you&#8217;ve been living under a rock, you&#8217;ve probably heard about the release of Google Chrome. Being a hardcore Firefox nut myself, I&#8217;m not just skeptical, I&#8217;m largely indifferent. With Firebug, I&#8217;ve got the perfect web developer environment, so I&#8217;m good to go. It would be hard to sell me on something else.


Google is [...]]]></description>
			<content:encoded><![CDATA[<p>
So unless you&#8217;ve been living under a rock, you&#8217;ve probably heard about <a href="http://googleblog.blogspot.com/2008/09/fresh-take-on-browser.html">the release</a> of <a href="http://www.google.com/chrome">Google Chrome</a>. Being a hardcore <a href="http://www.mozilla.com/">Firefox</a> nut myself, I&#8217;m not just skeptical, I&#8217;m largely indifferent. With <a href="https://addons.mozilla.org/en-US/firefox/addon/1843">Firebug</a>, I&#8217;ve got the perfect web developer environment, so I&#8217;m good to go. It would be hard to sell me on something else.
</p>
<p>
Google is a buzzworthy company, though, and I&#8217;ve already heard from everyone and their mom about how simple, clean and (most notably), <strong>fast</strong> the browser is. This piqued my interest. Time for more benchmarks!
</p>
<p>
I really thought I&#8217;d published more <a href="/tag/benchmarks/">benchmark articles</a> by now, but there were only two, so amending them was quick and easy. Here are the results:
</p>
<h3><a href="/article/try-catch-benchmark/">Try&#8230; Catch Benchmark</a></h3>
<p>
This benchmark was setup to see how quickly the standard browsers could execute code that was throwing (and catching) errors. <a href="/article/try-catch-benchmark/">Read the full article here.</a>
</p>
<table cellpadding="3" cellspacing="0" class="results">
<tr>
<th>Browser</th>
<th>Solo</th>
<th>With <code>try...catch</code></th>
<th>With <code>try...catch</code> and an error</th>
</tr>
<tr>
<td>Firefox 2</td>
<td>36 milliseconds</td>
<td>47 milliseconds</td>
<td class="error">32.917 seconds</td>
</tr>
<tr class="toggle">
<td>Firefox 3</td>
<td>3 milliseconds</td>
<td>4 milliseconds</td>
<td>156 milliseconds</td>
</tr>
<tr>
<td>Google Chrome</td>
<td class="best">0 milliseconds</td>
<td>6 milliseconds</td>
<td>69 milliseconds</td>
</tr>
<tr class="toggle">
<td>Internet Explorer 6</td>
<td>33 milliseconds</td>
<td>35 milliseconds</td>
<td>209 milliseconds</td>
</tr>
<tr>
<td>Internet Explorer 7</td>
<td>33 milliseconds</td>
<td>35 milliseconds</td>
<td>178 milliseconds</td>
</tr>
<tr class="toggle">
<td>Opera </td>
<td>6 milliseconds</td>
<td>10 milliseconds</td>
<td class="error">3.011 seconds</td>
</tr>
<tr>
<td>Safari 3</td>
<td>13 milliseconds</td>
<td>16 milliseconds</td>
<td>50 milliseconds</td>
</tr>
</table>
<p>
As you can see, <strong>Chrome</strong> is among the highest performers. It executes the plain code insanely fast (never more than 1 millisecond in any of my tests), and is only second to <strong>Safari 3</strong> in terms of catching errors quickly.
</p>
<h3><a href="/article/conditional-benchmarks/">Conditional Benchmarks</a></h3>
<p>
This benchmark is a little more abstract. The objective was to determine which conditional is fastest among <code>if</code>, <code>switch</code> and what I call an <strong>object conditional</strong>.
</p>
<table cellpadding="3" cellspacing="0" class="results">
<tr>
<th>Browser</th>
<th><code>if</code> block</th>
<th><code>switch</code> statement</th>
<th>object conditional</th>
</tr>
<tr>
<td>Firefox 2</td>
<td class="worst">444 milliseconds</td>
<td>425 milliseconds</td>
<td class="best">310 milliseconds</td>
</tr>
<tr class="toggle">
<td>Firefox 3</td>
<td class="worst">50 milliseconds</td>
<td class="best">38 milliseconds</td>
<td>42 milliseconds</td>
</tr>
<tr>
<td>Google Chrome</td>
<td class="best">11 milliseconds</td>
<td class="best">11 milliseconds</td>
<td>20 milliseconds</td>
</tr>
<tr class="toggle">
<td>Internet Explorer 6</td>
<td class="worst">353 milliseconds</td>
<td>347 milliseconds</td>
<td class="best">290 milliseconds</td>
</tr>
<tr>
<td>Internet Explorer 7</td>
<td class="worst">375 milliseconds</td>
<td>381 milliseconds</td>
<td class="best">344 milliseconds</td>
</tr>
<tr class="toggle">
<td>Opera 9.5</td>
<td class="best">50 milliseconds</td>
<td class="worst">55 milliseconds</td>
<td>54 milliseconds</td>
</tr>
<tr>
<td>Safari 3</td>
<td>150 milliseconds</td>
<td class="worst">156 milliseconds</td>
<td class="best">137 milliseconds</td>
</tr>
</table>
<p>
Turns out, that was no fluke earlier. <strong>Chrome easily blows away the competition</strong> here. I might question Google&#8217;s motives (and I certainly think it&#8217;s a tad shady to have renewed their contract with their now-competitor and then release competing software), but I applaud their speed of my beloved JavaScript.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/google-chrome-benchmarks/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>The &#8220;Last in a Loop&#8221; Bug</title>
		<link>http://scriptnode.com/article/the-last-in-a-loop-bug/</link>
		<comments>http://scriptnode.com/article/the-last-in-a-loop-bug/#comments</comments>
		<pubDate>Thu, 28 Aug 2008 09:46:03 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=80</guid>
		<description><![CDATA[The Problem

If you&#8217;ve had your hands in JavaScript for a while, chances are you&#8217;ve ran into this bug. You&#8217;ve got a bunch of elements you&#8217;re either adding to the
DOM or a bunch of listeners you&#8217;re attaching to elements. Either way, you keep getting the same result:
the last value in the loop. Here&#8217;s an example:


Let&#8217;s say [...]]]></description>
			<content:encoded><![CDATA[<h3>The Problem</h3>
<p>
If you&#8217;ve had your hands in JavaScript for a while, chances are you&#8217;ve ran into this bug. You&#8217;ve got a <strong>bunch of elements</strong> you&#8217;re either adding to the<br />
<acronym title="Document Object Model">DOM</acronym> or a bunch of listeners you&#8217;re attaching to elements. Either way, you keep getting the same result:<br />
<strong>the last value in the loop</strong>. Here&#8217;s an example:
</p>
<p>
Let&#8217;s say you&#8217;ve got a list of <strong>5 items</strong> and you want to listen to the <strong>click</strong> event for each.<br />
Many developers would immediately think of doing it this way:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var els = document.getElementById(&#8217;last-one-example-1&#8242;).getElementsByTagName(&#8217;LI&#8217;);</p>
<p>for (var i = 0; i &lt; els.length; i++) {<br />
	els[i].onclick = function() {<br />
		alert(&#8217;You clicked element #&#8217; + i);<br />
	};<br />
}<br />
</textarea></p>
<p>
You can try this example below:
</p>
<div class="section">
<ul id="last-one-example-1">
<li>Item #1 &#8211; click me!</li>
<li>Item #2 &#8211; click me!</li>
<li>Item #3 &#8211; click me!</li>
<li>Item #4 &#8211; click me!</li>
<li>Item #5 &#8211; click me!</li>
</ul>
</div>
<p><script type="text/javascript">
<!--//
(function() {</p>
<p>	var els = document.getElementById('last-one-example-1').getElementsByTagName('LI');</p>
<p>	for (var i = 0; i < els.length; i++) {
		els[i].onclick = function() {
			alert('You clicked element #' + i);
		};
	}</p>
<p>})();
//-->
</script></p>
<p>
No matter which element is clicked, the same result keeps appearing: <strong>You clicked element #5</strong>.<br />
This baffles many JavaScript programmers. So what&#8217;s going on here?
</p>
<p>
The issue here is a <strong>misunderstanding of <a href="http://www.jibbering.com/faq/faq_notes/closures.html">closure</a></strong>.<br />
In the above example, it&#8217;s assumed that the variable <code>i</code> will retain its value during the loop for that particular function call.<br />
But actually what&#8217;s happening is <strong>the click function is accessing the same <code>i</code> variable that the <code>for loop</code> accessed</strong>.<br />
So anytime <code>i</code> is checked, its value will be the same as it was when the loop finished.
</p>
<h3>A Solution</h3>
<p>
Usually what a developer wants to accomplish is a function listening to the click event that retains the value of<br />
<code>i</code> as it was during that iteration in the loop.<br />
Here&#8217;s a way to accomplish that behavior:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var els = document.getElementById(&#8217;last-one-example-2&#8242;).getElementsByTagName(&#8217;LI&#8217;);</p>
<p>for (var i = 0; i &lt; els.length; i++) {</p>
<p>	els[i].onclick = function(currentLoopValue) {<br />
		return function(e) {<br />
			alert(&#8217;You clicked element #&#8217; + currentLoopValue);<br />
		};<br />
	}(i);</p>
<p>}<br />
</textarea></p>
<p>
This pattern can be more than a little confusing. Let&#8217;s walk through it line-by-line, <strong>starting with line 5</strong>:
</p>
<ol>
<li value="5">
		This time we&#8217;re firing off a function immediately, allowing us to run some code within a closure to avoid <code>i</code> changing values on us.
	</li>
<li>We still want the <code>onclick</code> to be assigned a function to fire, so we return an anonymous function just like we did before.</li>
<li>We <code>alert</code> the item number just like we normally would (but this time it will work).</li>
<li>End the returned function.</li>
<li>
		End the <code>onclick</code> assignment.<br />
		This function gets fired off <strong>immediately</strong> because of the parentheses.<br />
		We pass <code>i</code> in, retaining its current loop value because of the function scope we declared on line 5.<br />
		This is probably the step that confuses developers the most.
	</li>
</ol>
<p>
Here is that example in action:
</p>
<div class="section">
<ul id="last-one-example-2">
<li>Item #1 &#8211; click me!</li>
<li>Item #2 &#8211; click me!</li>
<li>Item #3 &#8211; click me!</li>
<li>Item #4 &#8211; click me!</li>
<li>Item #5 &#8211; click me!</li>
</ul>
</div>
<p><script type="text/javascript">
<!--//
(function() {</p>
<p>	var els = document.getElementById('last-one-example-2').getElementsByTagName('LI');</p>
<p>	for (var i = 0; i < els.length; i++) {</p>
<p>		els[i].onclick = function(currentLoopValue) {
			return function(e) {
				alert('You clicked element #' + currentLoopValue);
			};
		}(i);</p>
<p>	}</p>
<p>})();
//-->
</script></p>
<p>
And it works the way you&#8217;d expect! What do you think?<br />
If you don&#8217;t quite understand the pattern, or have another method to use to solve this problem, I&#8217;d love to hear about it in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/the-last-in-a-loop-bug/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>MySQL Database Class</title>
		<link>http://scriptnode.com/article/mysql-database-class/</link>
		<comments>http://scriptnode.com/article/mysql-database-class/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 04:19:11 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[script-sunday]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=76</guid>
		<description><![CDATA[
I&#8217;ve been spending loads of time recently with a new project that&#8217;s supposed to be comprised mostly of
what I love doing the most: hardcore JavaScript.
Unfortunately, most front-ends aren&#8217;t much without a back-end to fall on, so I&#8217;ve had to hit the PHP pretty hard too.


When modifying the framework I had built, I noticed that the [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;ve been spending <strong>loads</strong> of time recently with a <a href="http://valadria.com/">new project</a> that&#8217;s supposed to be comprised mostly of<br />
what I love doing the most: hardcore <a href="/tag/javascript/">JavaScript</a>.<br />
Unfortunately, most front-ends aren&#8217;t much without a back-end to fall on, so I&#8217;ve had to hit the <a href="/tag/php">PHP</a> pretty hard too.
</p>
<p>
When modifying the framework I had built, I noticed that the old database class I was using was a little out of date. PHP5 is the new standard, shouldn&#8217;t we all<br />
be using <a href="http://us3.php.net/manual/en/book.pdo.php" title="PHP Data Object">PDO</a>? So I added migrating to PDO to my to-do list. But really, the class<br />
is a pretty good one. It&#8217;s certainly been <a href="http://dirtybeta.com/">useful</a> to me for, well, almost a few years now, give or take a few dozen tweaks.
</p>
<p>
So given the longevity of the script, I thought I&#8217;d offer it up for this week&#8217;s <a href="/tag/script-sunday/">Script Sunday</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
/**<br />
 * Database constructor<br />
 */<br />
class Database {</p>
<p>	protected<br />
		$connection,<br />
		$debug,<br />
		$debug_func;</p>
<p>	/**<br />
	 * Constructor method. Connects to the database<br />
	 * @public<br />
	 */<br />
    function __construct() {</p>
<p>		$this-&gt;debug = Array();<br />
		$this-&gt;debug_func = &#8216;debugNone&#8217;;</p>
<p>    }</p>
<p>	/**<br />
	 * Gets the number of affected rows from the last query<br />
	 * @return integer Number of affected rows<br />
	 * @public<br />
	 */<br />
    function affectedRows() {<br />
        return mysql_affected_rows($this-&gt;connection);<br />
    }</p>
<p>	/**<br />
	 * Checks a table to see if a key/value pair exists<br />
	 * @param string table The table to check<br />
	 * @param string field The field in the table<br />
	 * @param string value The value of the field to check<br />
	 * @return bool Returns true if it found a matching row<br />
	 * @public<br />
	 */<br />
    function checkField($table, $field, $value, $and = &#8221;) {</p>
<p>		$qry = sprintf(&#8217;<br />
			SELECT<br />
				%s<br />
			FROM<br />
				%s<br />
			WHERE<br />
				%s = &#8220;%s&#8221;<br />
				%s<br />
			&#8216;,<br />
			$field,<br />
			$table,<br />
			$field,<br />
			$value,<br />
			$and<br />
		);</p>
<p>        $res = $this-&gt;query($qry);<br />
		$row = $this-&gt;fetchRow($res);</p>
<p>        return ($row ? true : false);</p>
<p>    }</p>
<p>	/**<br />
	 * Cleans a value for the DB<br />
	 * @param str $value The value to clean<br />
	 * @return str The cleaned string<br />
	 */<br />
	function clean($value) {</p>
<p>		$value = stripslashes($value);<br />
		$value = trim($value);<br />
		$value = str_replace(&#8221;&#8216;&#8221;, &#8220;\&#8217;&#8221;, $value);</p>
<p>		return $value;</p>
<p>	}</p>
<p>	/**<br />
	 * Connect to the database<br />
	 * @param string db_server The database server to connect to (often localhost)<br />
	 * @param string db_user The user to send to the server<br />
	 * @param string db_password The user&#8217;s password<br />
	 * @param string db_name The name of the database to use<br />
	 * @public<br />
	 */<br />
    function connect($db_server, $db_user, $db_password, $db_name) {</p>
<p>        $this-&gt;connection = mysql_connect($db_server, $db_user, $db_password);<br />
        $this-&gt;select($db_name, $this-&gt;connection);</p>
<p>        return ($this-&gt;connection ? true : false);</p>
<p>    }</p>
<p>	function debugNone() {}</p>
<p>	/**<br />
	 * Adds a debug message to $debug<br />
	 * @param str The debug message<br />
	 * @public<br />
	 */<br />
	function debugPut($debug) {<br />
		$this-&gt;debug[] = $debug;<br />
	}</p>
<p>	/**<br />
	 * Deletes rows from the database<br />
	 * @param string table The table to query<br />
	 * @param string where There WHERE clause in the query<br />
	 * @param integer limit How many rows to limit (default is 1)<br />
	 * @return integer Number of affected rows<br />
	 * @public<br />
	 */<br />
    function deleteRows($table, $where, $limit = 1) {</p>
<p>		$limit = ($limit ? &#8216;LIMIT &#8216; . $limit : &#8221;);</p>
<p>        $qry = &#8216;DELETE FROM &#8216; . $table . &#8216;<br />
				WHERE &#8216; . $where . &#8216;<br />
				&#8216; . $limit;</p>
<p>        $this-&gt;query($qry);</p>
<p>		return $this-&gt;affectedRows();</p>
<p>    }</p>
<p>	/**<br />
	 * Retrieves a row from the database<br />
	 * @param string result The result set returned from the query<br />
	 * @return array Associatve index of the retrieved row<br />
	 */<br />
    function fetchRow($res) {<br />
        return @mysql_fetch_assoc($res);<br />
    }</p>
<p>	/**<br />
	 * Get a single row from the database<br />
	 * @param qry The query to send<br />
	 * @return array Associative array of the row<br />
	 */<br />
	function getRow($qry) {</p>
<p>		$res = $this-&gt;query($qry);<br />
		$row = $this-&gt;fetchRow($res);</p>
<p>		return $row;</p>
<p>	}</p>
<p>	/**<br />
	 * Retreive rows from the database<br />
	 * @param qry The query to get the rows<br />
	 * @param array Numeric array of the rows<br />
	 */<br />
	function getRows($qry) {</p>
<p>		$rows = Array();<br />
		$res  = $this-&gt;query($qry);</p>
<p>		while ($row = $this-&gt;fetchRow($res)) {<br />
			$rows[] = $row;<br />
		}</p>
<p>		return $rows;</p>
<p>	}</p>
<p>	/**<br />
	 * Format a query for insertion into the database<br />
	 * @param string table The table to insert into<br />
	 * @param array pairs Key value pairs of the fields and values to insert<br />
	 * @return string The prepared query, ready to insert<br />
	 */<br />
    function formatInsert($table, $pairs) {</p>
<p>        foreach ($pairs as $field =&gt; $value) {</p>
<p>			$fields .= $field . &#8216;,&#8217;;</p>
<p>			if (!is_numeric($value)) {<br />
				$value = $this-&gt;clean($value);<br />
			}</p>
<p>			$values .= &#8220;&#8216;$value&#8217;,&#8221;;</p>
<p>        }</p>
<p>		$fields = substr($fields, 0, -1);<br />
		$values = substr($values, 0, -1);</p>
<p>		$qry = sprintf(&#8221;<br />
			INSERT INTO<br />
				$table<br />
			($fields)<br />
			VALUES<br />
				($values)<br />
		&#8220;);</p>
<p>        return $qry;</p>
<p>    }</p>
<p>	/**<br />
	 * Formats an update query based on a key/value array<br />
	 * @param string table The name of the table<br />
	 * @param array pairs The key/value pair of the fields/values<br />
	 * @param string where The WHERE clause of the array (default: 1)<br />
	 * @param integer limit The limit on tbe query<br />
	 * @return string The prepared query<br />
	*/<br />
    function formatUpdate($table, $pairs, $where = &#8216;1&#8242;, $limit = false) {</p>
<p>        foreach ($pairs as $key =&gt; $value) {</p>
<p>			if (!is_numeric($value)) {<br />
				$value = $this-&gt;clean($value);<br />
			}</p>
<p>			$set .= &#8220;$key = &#8216;$value&#8217;, &#8220;;</p>
<p>        }</p>
<p>        $set   = substr($set, 0, -2);<br />
		$limit = ($limit ? &#8216; LIMIT &#8216; . $limit : &#8221;);</p>
<p>		$qry = sprintf(&#8221;<br />
			UPDATE<br />
				$table<br />
			SET<br />
				$set<br />
			WHERE<br />
				$where<br />
			$limit<br />
		&#8220;);</p>
<p>        return $qry;</p>
<p>    }</p>
<p>	/**<br />
	 * Get the id of the last inserted row<br />
	 * @return integer They id (if it exists) of the last inserted row<br />
	*/<br />
    function getID() {<br />
        return mysql_insert_id($this-&gt;connection);<br />
    }</p>
<p>	/**<br />
	 * Inserts rows into the database<br />
	 * @param string table The table to send the query to<br />
	 * @param array pairs The key/value pairs to insert into the database<br />
	 * @return integer Number of affected rows<br />
	*/<br />
	function insertRows($table, $pairs) {<br />
		return $this-&gt;query($this-&gt;formatInsert($table, $pairs));<br />
	}</p>
<p>	/**<br />
	 * Gets the number of rows from a result set<br />
	 * @return integer Number of rows<br />
	*/<br />
    function numRows($res) {<br />
        return mysql_num_rows($res);<br />
    }</p>
<p>	/**<br />
	 * Send a query to the database<br />
	 * @param string qry The query to send<br />
	 * @return string A reference to the result set<br />
	*/<br />
    function query($qry) {</p>
<p>		$func = $this-&gt;debug_func;<br />
		$this-&gt;$func($qry);</p>
<p>        return mysql_query($qry, $this-&gt;connection);</p>
<p>    }</p>
<p>	/**<br />
	 * Select a database on the server<br />
	 * @param string db_name The name of the database<br />
	 * @return bool Returns true on success and false on failure<br />
	*/<br />
    function select($db_name, $connection = null) {</p>
<p>		if ($connection) {<br />
			$this-&gt;connection = &amp;$connection;<br />
		}</p>
<p>        return mysql_select_db($db_name, $this-&gt;connection);</p>
<p>    }</p>
<p>	/**<br />
	 * Turns on or off the debug option<br />
	 * @param bool debug The new value of the debug option<br />
	*/<br />
	function setDebug($debug) {<br />
		if ($debug) {<br />
			$this-&gt;debug_func = &#8216;debugPut&#8217;;<br />
		} else {<br />
			$this-&gt;debug_func = &#8216;debugNone&#8217;;<br />
		}<br />
	}</p>
<p>	/**<br />
	 * Updates rows in the database<br />
	 * @param string table The table to send the query to<br />
	 * @param array pairs The key/value pairs to insert into the database<br />
	 * @param string where The WHERE clause of the array (default: 1)<br />
	 * @param integer limit The limit on tbe query<br />
	 * @return integer Number of affected rows<br />
	*/<br />
	function updateRows($table, $pairs, $where = &#8216;1&#8242;, $limit = false) {<br />
		return $this-&gt;query($this-&gt;formatUpdate($table, $pairs, $where, $limit));<br />
	}</p>
<p>}<br />
</textarea></p>
<p>
And here&#8217;s a quick example of how to use it:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$db = new Database();<br />
$db-&gt;connect($server, $user, $password, $db_name);</p>
<p>$query = &#8216;SELECT * FROM users&#8217;;<br />
$users = $db-&gt;getRows($query);</p>
<p>foreach ($users as $user) {<br />
	echo &#8216;Username: &#8216; . $user['username'] . &#8216;&lt;br&gt;&#8217;;<br />
}<br />
</textarea></p>
<ul>
<li><a href="/assets/php/db-class/database.php.txt">[Download database.php.txt]</a> (6,848 bytes)</li>
<li><a href="/assets/php/db-class/db-class.zip">[Download db-class.zip]</a> (1,966 bytes)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/mysql-database-class/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Quickly Update DocumentRoot in Apache2</title>
		<link>http://scriptnode.com/article/quickly-update-documentroot-in-apache2/</link>
		<comments>http://scriptnode.com/article/quickly-update-documentroot-in-apache2/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 19:33:50 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[script-sunday]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=63</guid>
		<description><![CDATA[
For today&#8217;s Script Sunday I thought I&#8217;d take a go back in time a little and provide an old utility that I still to this day find useful.
It&#8217;s a script I wrote called ChangeLocalHost which alters the DocumentRoot in apache2. An example of its use would be:


./clh.php local-site.com/public_html/


Note: you must be root to run it


Given [...]]]></description>
			<content:encoded><![CDATA[<p>
For today&#8217;s <a href="/tag/script-sunday/">Script Sunday</a> I thought I&#8217;d take a go back in time a little and provide an old utility that I still to this day find useful.<br />
It&#8217;s a script I wrote called <code>ChangeLocalHost</code> which alters the <code>DocumentRoot</code> in <code>apache2</code>. An example of its use would be:
</p>
<p>
<code>./clh.php local-site.com/public_html/</code>
</p>
<p>
<em>Note: you must be <code>root</code> to run it</em>
</p>
<p>
Given this command, the script will change <code>DocumentRoot</code> to <strong>local-site.com/public_html/</strong> and restart <code>apache2</code>.<br />
I work on <a href="http://dirtybeta.com/">a lot</a> of <a href="http://valadria.com/">websites</a> (developing most of them on my laptop running <code>apache2</code>)<br />
so I use this script constantly.
</p>
<p>
Here&#8217;s the code:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
#!/usr/bin/php<br />
&lt;?php</p>
<p>/*<br />
ChangeLocalHost v0.1 &#8211; last updated Mar 07 2007<br />
Must be root to execute. Alters the DocumentRoot in Apache2&#8217;s conf file, then restarts Apache2.<br />
*/</p>
<p>$obj_clh = new ChangeLocalHost(&#8217;/etc/apache2/sites-available/&#8217;, &#8216;default&#8217;, &#8216;/home/www/&#8217;);</p>
<p>$obj_clh-&gt;setArgs($_SERVER['argv']);<br />
$obj_clh-&gt;run();</p>
<p>/**<br />
 * CLH class constructor<br />
 * @constructor<br />
 */<br />
class ChangeLocalHost {</p>
<p>	private $arr_args,<br />
			$bit_msgs,<br />
			$str_dir,<br />
			$str_file,<br />
			$str_pre;</p>
<p>	protected $str_version;</p>
<p>	/**<br />
	 * Constructor method<br />
	 * @param string str_dir The location of the Apache conf file to mod<br />
	 * @param string str_file The name of the Apache conf file to mod<br />
	 * @param string str_pre The needle to search for in the conf file<br />
	 */<br />
	function __construct($str_dir, $str_file, $str_pre) {</p>
<p>		$this-&gt;str_version = &#8216;ChangeLocalHost v0.1&#8242;;</p>
<p>		$this-&gt;arr_args = Array();<br />
		$this-&gt;bit_msgs = true;<br />
		$this-&gt;str_dir  = $str_dir;<br />
		$this-&gt;str_file = $str_file;<br />
		$this-&gt;str_pre  = $str_pre;</p>
<p>	}</p>
<p>	/**<br />
	 * Modify Apache&#8217;s DocumentRoot<br />
	 * @param string str_file The (conf) file to mod<br />
	 * @param string str_new_dir The new directory to set as DocumentRoot<br />
	 * @private<br />
	 */<br />
	private function alterLocalHost($str_file, $str_new_dir) {</p>
<p>		$str_contents = file_get_contents($str_file);</p>
<p>		if (!$str_contents) {<br />
			$this-&gt;showError(&#8217;Could not read &#8216; . $str_file);<br />
		}</p>
<p>		$int_begin    = strpos($str_contents, $this-&gt;str_pre);<br />
		$int_end      = strpos(substr($str_contents, $int_begin), &#8220;\n&#8221;);<br />
		$str_search   = substr($str_contents, $int_begin, $int_end);<br />
		$str_contents = str_replace($str_search, $str_new_dir, $str_contents);<br />
		$bit_written  = file_put_contents($str_file, $str_contents);</p>
<p>		if ($bit_written) {<br />
			$this-&gt;showMessage(&#8217;Successfully set DocumentRoot to &#8216; . $str_new_dir);<br />
		} else {<br />
			$this-&gt;showError(&#8217;Could not write &#8216; . $str_file);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Validates the new directory to set<br />
	 * @param string str_new_dir The potential new directory<br />
	 * @private<br />
	 */<br />
	private function checkLocalHost($str_new_dir) {</p>
<p>		$str_set_to = $this-&gt;str_pre . $str_new_dir;</p>
<p>		if (is_dir($str_set_to)) {</p>
<p>			$this-&gt;setLocalHost($str_set_to);<br />
			$this-&gt;restartApache2();</p>
<p>		} else {<br />
			$this-&gt;showError($str_set_to . &#8216; is not a valid directory.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Ensures this app is being executed as root<br />
	 * @private<br />
	 */<br />
	private function checkRoot() {</p>
<p>		// Make sure user is root<br />
		$str_command = &#8216;whoami&#8217;;</p>
<p>		exec($str_command, $arr_output, $int_return);</p>
<p>		if ($arr_output[0] != &#8216;root&#8217;) {<br />
			$this-&gt;showError(&#8217;You must be root to run this program.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Makes a backup of the Apache conf file<br />
	 * @param string str_source The original to copy<br />
	 * @param string str_new The location of the backup<br />
	 * @return bool Whether the copy was successful or not<br />
	 * @private<br />
	 */<br />
	private function makeCopy($str_source, $str_new) {</p>
<p>		$bit_copy = copy($str_source, $str_new);</p>
<p>		if (!$bit_copy) {<br />
			$this-&gt;showError(&#8217;Could not make copy of &#8216; . $str_source);<br />
		}</p>
<p>		return true;</p>
<p>	}</p>
<p>	/**<br />
	 * Restarts Apache2<br />
	 * @private<br />
	 */<br />
	private function restartApache2() {</p>
<p>		$str_command = &#8216;apache2ctl restart&#8217;;</p>
<p>		exec($str_command, $arr_output, $int_return);</p>
<p>		if ($int_return &gt; 0) {<br />
			$this-&gt;showError(&#8217;Could not restart Apache2.&#8217; . $str_source);<br />
		}</p>
<p>		$this-&gt;showMessage(&#8217;Successfully restarted Apache2.&#8217;);</p>
<p>	}</p>
<p>	/**<br />
	 * Executes the script<br />
	 */<br />
	function run() {</p>
<p>		$this-&gt;checkRoot();</p>
<p>		$str_new_dir = $this-&gt;arr_args[1];</p>
<p>		switch ($this-&gt;arr_args[1]) {</p>
<p>			case &#8216;-c&#8217; :<br />
			case &#8216;&#8211;current&#8217; :<br />
				$this-&gt;showCurrent();<br />
				break;</p>
<p>			case &#8221; :<br />
			case &#8216;-h&#8217; :<br />
			case &#8216;&#8211;help&#8217; :<br />
				$this-&gt;showHelp();<br />
				break;</p>
<p>			case &#8216;-q&#8217; :<br />
			case &#8216;&#8211;quiet&#8217; :<br />
				$str_new_dir    = $this-&gt;arr_args[2];<br />
				$this-&gt;bit_msgs = false;<br />
				break;</p>
<p>			case &#8216;-v&#8217; :<br />
			case &#8216;&#8211;version&#8217; :<br />
				$this-&gt;showVersion();<br />
				break;</p>
<p>			default :<br />
				break;</p>
<p>		}</p>
<p>		$this-&gt;checkLocalHost($str_new_dir);<br />
		exit(0);</p>
<p>	}</p>
<p>	/**<br />
	 * Create a copy of the arguments global<br />
	 * @param array array_args The arguments to set<br />
	 */<br />
	function setArgs($arr_args) {<br />
		$this-&gt;arr_args = &amp;$arr_args;<br />
	}</p>
<p>	/**<br />
	 * Call the other methods to initiate the altering of the DocumentRoot<br />
	 * @param string str_new_dir The new value of DocumentRoot<br />
	 * @private<br />
	 */<br />
	private function setLocalHost($str_new_dir) {</p>
<p>		$str_ext    = &#8216;.bak&#8217;;<br />
		$str_file   = ($this-&gt;str_dir . $this-&gt;str_file);<br />
		$str_backup = $str_file . $str_ext;</p>
<p>		if (is_file($str_file)) {</p>
<p>			if ($this-&gt;makeCopy($str_file, $str_backup)) {<br />
				$this-&gt;showMessage(&#8217;Copied backup of &#8216; . $this-&gt;str_file . &#8216; to &#8216; . $this-&gt;str_file . $str_ext);<br />
			}</p>
<p>			$this-&gt;alterLocalHost($str_file, $str_new_dir);</p>
<p>		} else {<br />
			$this-&gt;showError($str_file . &#8216; cannot be found.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Show what DocumentRoot is currently set to<br />
	 * @private<br />
	 */<br />
	private function showCurrent() {</p>
<p>		$str_file = ($this-&gt;str_dir . $this-&gt;str_file);</p>
<p>		if (is_file($str_file)) {</p>
<p>			$str_contents = file_get_contents($str_file);</p>
<p>			if (!$str_contents) {<br />
				$this-&gt;showError(&#8217;Could not read &#8216; . $str_file);<br />
			}</p>
<p>			$int_begin  = strpos($str_contents, $this-&gt;str_pre);<br />
			$int_end    = strpos(substr($str_contents, $int_begin), &#8220;\n&#8221;);<br />
			$str_search = substr($str_contents, $int_begin, $int_end);</p>
<p>			$this-&gt;showMessage(&#8217;The current DocumentRoot is: &#8216; . $str_search);<br />
			exit;</p>
<p>		} else {<br />
			$this-&gt;showError($str_file . &#8216; cannot be found.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Display a message and exit<br />
	 * @param string str_error The message to display<br />
	 * @private<br />
	 */<br />
	private function showError($str_error) {</p>
<p>		echo &#8216;Error: &#8216; . $str_error . &#8220;\n&#8221;;</p>
<p>		exit(1);</p>
<p>	}</p>
<p>	/**<br />
	 * Show the help text and exit<br />
	 * @private<br />
	 */<br />
	private function showHelp() {</p>
<p>		$str_help .= &#8216;Usage: clh [DIRECTORY]&#8230; [OPTIONS]&#8216; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;Alter the DocumentRoot in Apache2.&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -c, &#8211;current  display current DocumentRoot and exit&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -h, &#8211;help     display this help and exit&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -q, &#8211;quiet    suppress most messages&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -v, &#8211;version  output version information and exit&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8220;\n&#8221;;<br />
		$str_help .= &#8216;Report bugs to &lt;scriptnode@gmail.com&gt;.&#8217; . &#8220;\n&#8221;; // Hahahaha</p>
<p>		echo $str_help;</p>
<p>		exit(0);</p>
<p>	}</p>
<p>	/**<br />
	 * Display a message to the user<br />
	 * @param string str_message The message to show<br />
	 * @private<br />
	 */<br />
	private function showMessage($str_message) {</p>
<p>		if ($this-&gt;bit_msgs) {<br />
			echo $str_message . &#8220;\n&#8221;;<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Attempt to be more like a real application by displaying the version<br />
	 * @private<br />
	 */<br />
	private function showVersion() {</p>
<p>		echo $this-&gt;str_version . &#8220;\n&#8221;;</p>
<p>		exit(0);</p>
<p>	}</p>
<p>}<br />
</textarea></p>
<p>
You&#8217;ll notice that the script is at least a year and a half old.<br />
Usually if code of mine is more than a year old, it&#8217;s completely unusuable because my <a href="/article/my-new-coding-habits/">habits change pretty often</a>.<br />
But I think I&#8217;ve finally gotten to that sweet spot where it&#8217;s not total garbage, it just needs tweaking.
</p>
<p>
I was surprised that the code isn&#8217;t too bad really. It&#8217;s easily readable and well organized. There are many things that I wouldn&#8217;t have done were I to write this again;<br />
for example, I stopped using type prefixes long ago (such as an array of users as <code>$arr_users</code>). I understand why I used to do this, but it&#8217;s not necessary<br />
and only clutters up the code.
</p>
<p>
Anyway, I find this script useful and I thought someone else might too. Enjoy!
</p>
<ul>
<li><a href="/assets/php/clh/clh.php.txt">[Download clh.php.txt]</a> (6,614 bytes)</li>
<li><a href="/assets/php/clh/clh.zip">[Download clh.zip]</a> (1,975 bytes)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/quickly-update-documentroot-in-apache2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Upcoming Bay Area Events</title>
		<link>http://scriptnode.com/article/san-francisco-javascript-meetup-2/</link>
		<comments>http://scriptnode.com/article/san-francisco-javascript-meetup-2/#comments</comments>
		<pubDate>Sat, 09 Aug 2008 20:00:11 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[links]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=16</guid>
		<description><![CDATA[San Francisco JavaScript Meetup #3

If you&#8217;re in the bay area, check out The SF JavaScript Meetup #3, Monday, August 18th at 7:00PM. Last time, the infamous Douglas Crockford was there, so it&#8217;s sure to be a hoot! Here are the details:


As always, we will have plenty of awesome JavaScripters attending, a number of great talks [...]]]></description>
			<content:encoded><![CDATA[<h3>San Francisco JavaScript Meetup #3</h3>
<p>
If you&#8217;re in the bay area, check out <a href="http://javascript.meetup.com/4/calendar/8444425/">The SF JavaScript Meetup #3</a>, Monday, August 18th at 7:00PM. Last time, the infamous <a href="http://javascript.crockford.com/">Douglas Crockford</a> was there, so it&#8217;s sure to be a hoot! Here are the details:
</p>
<blockquote><p>
As always, we will have plenty of awesome JavaScripters attending, a number of great talks on cutting-edge scripting concepts, and excellent networking potential. Come and hang out with the best scripters in the Bay Area, learn a lot, eat free food, and have fun.
</p>
</blockquote>
<h3>The agenda</h3>
<ol>
<li>7:00PM &#8211; Event starts and food (&#8230;and lots of it!) will be ready for eating</li>
<li>7:20PM &#8211; A few words from our hosts, sponsors, and us</li>
<li>7:30PM &#8211; An hour of high-quality talks and demos (5&#215;12min)</li>
<li>8:30PM &#8211; Networking, talking, learning, discussing, more questions for speakers, more eating, whatever&#8230;</li>
<li>9:30PM &#8211; Start to wrap things up</li>
</ol>
<h3>The Address</h3>
<address>
580 Market Street, 6th Floor<br/><br />
San Francisco CA, 94104<br/><br />
</address>
<p>
<a href="http://richter.paletteswap.com">I&#8217;ll</a> be there, as will many of my <a href="http://fehrenbacher.com/">fellow</a> <a href="http://boldify.com/">front-end</a> <a href="http://foohack.com/">engineer</a> <a href="http://seldo.com/">buddies</a>.
</p>
<div id="y-map"></div>
<p><br/><!-- fail :( --></p>
<p><script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.8&amp;appid=DRwW0ojV34EtkDJlqEE75NnShbxh7e5j.5hukcQLXTe.KviHouC0PKs0lVDvo2M-"></script></p>
<p><script type="text/javascript">
(function() {
var map = new YMap(document.getElementById('y-map'));
map.addTypeControl();
map.addZoomLong();
map.addPanControl();
map.setMapType(YAHOO_MAP_REG);
map.drawZoomAndCenter("580 Market Street, 6th Floor, San Francisco CA, 94104", 4);
})();
</script></p>
<h3>Oh, and An Event Apart</h3>
<p>
Also (though I&#8217;m sure you&#8217;ve heard of this one), there&#8217;s <a href="http://aneventapart.com/">An Event Apart</a>: a two-day conference featuring <a href="http://www.ericmeyeroncss.com/">Eric Meyer</a> and <a href="http://www.zeldman.com/">Jeffrey Zeldman</a>, maintained by the good folks who run <a href="http://alistapart.com/">A List Apart</a>. This is another one I&#8217;m attending. Hope to see you there!</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/san-francisco-javascript-meetup-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript&#8217;s Object Literal Notation in PHP</title>
		<link>http://scriptnode.com/article/javascripts-object-literal-notation-in-php/</link>
		<comments>http://scriptnode.com/article/javascripts-object-literal-notation-in-php/#comments</comments>
		<pubDate>Fri, 25 Jul 2008 19:33:20 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=42</guid>
		<description><![CDATA[
I&#8217;ve found that the more I code in JavaScript, the more I enjoy its expressive syntax over other that of other languages. Object literals, for example, are among my most commonly used patterns:


myObject = {
    child : {
        key : &#8216;value&#8217;
    },
 [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;ve found that the more I code in JavaScript, the more I enjoy its expressive syntax over other that of other languages. Object literals, for example, are among my most commonly used patterns:
</p>
<p><textarea class="javascript" name="code" cols="50" rows="10"><br />
myObject = {<br />
    child : {<br />
        key : &#8216;value&#8217;<br />
    },<br />
    foo : &#8216;bar&#8217;<br />
};<br />
</textarea></p>
<p>
Sometimes I&#8217;ll even forget which language I&#8217;m in and I&#8217;ll try something like:
</p>
<p><textarea class="php" name="code" cols="50" rows="10"><br />
$myObject = object(&#8217;key&#8217; => &#8216;value&#8217;);<br />
</textarea></p>
<p>
Which gives the result: <code><strong>Parse error</strong>: syntax error, unexpected T_DOUBLE_ARROW in test.php on line 1</code>
</p>
<p>
What you <strong>can</strong> use in PHP, which are quite elegant and expressive, are associative arrays:
</p>
<p><textarea class="php" name="code" cols="50" rows="10"><br />
$myObject = array(<br />
    &#8216;child&#8217; =&gt; array(<br />
        &#8216;key&#8217; =&gt; &#8216;value&#8217;<br />
    ),<br />
    &#8216;foo&#8217; =&gt; &#8216;bar&#8217;<br />
);<br />
</textarea></p>
<p>
But if you were depending on an object for one reason or another, you can use typecasting to make PHP&#8217;s syntax more like that of JavaScript:
</p>
<p><textarea class="php" name="code" cols="50" rows="10"><br />
$myObject = (object) array(<br />
    &#8216;child&#8217; =&gt; (object) array(<br />
        &#8216;key&#8217; =&gt; &#8216;value&#8217;<br />
    ),<br />
    &#8216;foo&#8217; =&gt; &#8216;bar&#8217;<br />
);<br />
</textarea></p>
<p>
(Note that the <code>(object)</code> typecasting operator is needed at each level in the array.)<br />
This will also help eliminate strict warnings. Because though you <strong>can</strong> (depending on your <code>php.ini</code> settings) use this syntax&#8230;
</p>
<p><textarea class="php" name="code" cols="50" rows="10"><br />
$myObject->child->key = &#8216;value&#8217;;<br />
</textarea></p>
<p>
&#8230; it may give you this warning: <code><strong>Strict standards</strong>: Creating default object from empty value in test.php on line 1</code>
</p>
<p>
This PHP pattern to me is easily readable and makes the language more expressive, like our good friend JavaScript.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/javascripts-object-literal-notation-in-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Interview Questions Part 1: PHP</title>
		<link>http://scriptnode.com/article/interview-questions-part-1-php/</link>
		<comments>http://scriptnode.com/article/interview-questions-part-1-php/#comments</comments>
		<pubDate>Sat, 12 Jul 2008 09:08:04 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[careers]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[questions]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=39</guid>
		<description><![CDATA[
I interview a lot of people. Sometimes for a specific task, and sometimes just because we need more engineering power. In the latter case, it&#8217;s
usually enough to be a good, experienced engineer in almost any language. But usually we&#8217;re hiring for a job heavy on one language or another, and it&#8217;s my job
to find out [...]]]></description>
			<content:encoded><![CDATA[<p>
I interview a lot of people. Sometimes for a specific task, and sometimes just because we need more engineering power. In the latter case, it&#8217;s<br />
usually enough to be a good, experienced engineer in almost any language. But usually we&#8217;re hiring for a job heavy on one language or another, and it&#8217;s my job<br />
to find out if the candidate is fluent.
</p>
<p>
This is the first part of many articles I&#8217;m going to write about common interview questions in the vague and mysterious world of web development.<br />
There are of course an almost infinite amount of questions one <strong>could</strong> be asked during an interview, but my questions are typically going to be<br />
more about syntax and semantics than the probably more revealing questions on algorithms and problem-solving.
</p>
<p>
Without further ado, here are some common questions engineers get asked to see if they understand the basic syntax of <a href="http://php.net/">PHP</a>.
</p>
<ul>
<li><a href="#q-1">What are the differences between single and double quotes?</a></li>
<li><a href="#q-2">What are the differences between <code>include()</code> and <code>require()</code>?</a></li>
<li><a href="#q-3">What does the <code>===</code> operator do?</a></li>
<li><a href="#q-4">What does <code>$$</code> signify?</a></li>
<li><a href="#q-5">What are the various ways to append to an index array?</a></li>
<li><a href="#q-6">How do you debug in PHP?</a></li>
<li><a href="#q-7">Create a class and extend it.</a></li>
</ul>
<p><a name="q-1"></a></p>
<h3><abbr title="Question">Q</abbr>: What are the differences between single and double quotes?</h3>
<p>
<strong><abbr title="Answer">A</abbr>:</strong><br />
The primary difference is that a string enclosed with double quotes is parsed. A string enclosed in single quotes is just a string literal.
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
var $foo = &#8216;bar&#8217;;</p>
<p>echo &#8216;The value of foo is: $foo&#8217;; // The value of foo is: $foo<br />
echo &#8220;The value of foo is: $foo&#8221;; // The value of foo is: bar<br />
</textarea></p>
<p><a name="q-2"></a></p>
<h3><abbr title="Question">Q</abbr>: What are the differences between <code>include()</code> and <code>require()</code>?</h3>
<p>
<strong><abbr title="Answer">A</abbr>:</strong><br />
The most prominent difference is that <code>require()</code> will throw an error if it fails to include the given file, and <code>include()</code> will not.
</p>
<p><a name="q-3"></a></p>
<h3><abbr title="Question">Q</abbr>: What does the <code>===</code> operator do?</h3>
<p>
<strong><abbr title="Answer">A</abbr>:</strong><br />
Triple equals checks for both value and type:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$foo = &#8216;bar&#8217;;<br />
$pos = strpos($foo, &#8216;b&#8217;);</p>
<p>if ($pos) {} // false: 0 is a falsy value<br />
if ($pos !== false) {} // true: 0 is not of the same type as false<br />
</textarea></p>
<p>
I like to ask if the engineer can think of an example (like the one above).<br />
It&#8217;s almost guaranteed that a programmer that has been developing in PHP for an extended period needed <code>===</code> before.
</p>
<p><a name="q-4"></a></p>
<h3><abbr title="Question">Q</abbr>: What does <code>$$</code> signify?</h3>
<p>
<strong><abbr title="Answer">A</abbr>:</strong><br />
Double dollar sign signifies a variable variable:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$color = &#8216;red&#8217;;<br />
$red = &#8216;#ff0000&#8242;;</p>
<p>echo $color; // red<br />
echo $$color; // #ff0000<br />
</textarea></p>
<p><a name="q-5"></a></p>
<h3><abbr title="Question">Q</abbr>: What are the various ways to append to an index array?</h3>
<p>
<strong><abbr title="Answer">A</abbr>:</strong><br />
[see code]
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$my_array = array(1, 2, 3);</p>
<p>$my_array[] = 4;<br />
array_push($my_array, 5, 6);</p>
<p>$my_array[count($my_array)] = 7; // This is possible but dumb<br />
</textarea></p>
<p>
I like this question because it&#8217;s easy on the surface, and engineers will almost always get the first two. When I say there&#8217;s one more way, an engineer&#8217;s<br />
response is usually pretty revealing. Getting an answer like, &#8220;No there&#8217;s not,&#8221; shows (unearned) arrogance.<br />
Candidates that figure it out on their own show thinking on their feet.
</p>
<p><a name="q-6"></a></p>
<h3><abbr title="Question">Q</abbr>: How do you debug in PHP?</h3>
<p>
I think it&#8217;s probably most common for developers to use the quick-and-dirty <code>echo</code> statement. A better practice is to use <code>error_log</code><br />
or an external debugging library, because they won&#8217;t muck up the page and potentially cause other bugs.
</p>
<p><a name="q-7"></a></p>
<h3><abbr title="Question">Q</abbr>: Create a class and extend it.</h3>
<p>
Not really a question, but still important.<br />
I also ask about constructors and deconstructors, and make sure the candidate knows how to call the extended class&#8217;s constructor:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
class Foo {<br />
	function __construct() {}<br />
	private function privateMethod() {}<br />
	public function publicMethod() {}<br />
}</p>
<p>class Bar extends Foo {<br />
	function __construct() {<br />
		parent::__construct();<br />
	}<br />
}<br />
</textarea></p>
<p>
I also like to ask if <code>public</code> is required (it&#8217;s not because it&#8217;s the default state), and make sure that the engineer knows about <code>protected</code><br />
as well.<br />
I like to have conversations about object-oriented programming rather than just asking syntax questions, because I&#8217;ve found it&#8217;s easier.
</p>
<p>
That&#8217;s it, really. These questions are just to see if an engineer is familiar with the surface of the language.<br />
It could be argued that PHP is simple and quick to learn, and that these questions would shine a positive light on someone who spent a few hours reading about<br />
PHP, and a negative light on experienced engineers who are fantastic but not very familiar with PHP.<br />
It&#8217;s a valid argument, but again, this is just to test PHP knowledge.
</p>
<p>
If you know any questions similar to these, I&#8217;d love to hear about them in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/interview-questions-part-1-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
