I don’t care for a lot of the questions that I’ve been asked on interviews. Over time, I want to post a number of common, real-life PHP questions that I think would be more accurate at assessing how well someone knows PHP. Naturally, the person interviewing should get the question right, but the speed and depth of the response should indicate how well they know the language.
This is an easy one. If you’re a PHP developer, you should be able to figure this out pretty quickly!
Scenario:
There are 2 files involved: skin.php and home.php. You load home.php in your browser, and the page title gets set, and the content gets output. Why doesn’t the navigation get displayed?
[php]
<?
// skin.php
if( ! HIDE_NAV )
$nav = getNav();
function getNav()
{
return ‘
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog.php">Blog</a></li>
<li><a href="/about.php">About Us</a></li>
<li><a href="/contact.php">Contact Us</a></li>
</ul>’;
}
echo ‘
<html>
<head>
<title>’ . $title . ‘</title>
</head>
<body>
‘ . $nav . ‘
‘ . $content . ‘
</body>
</html>’;
?>
[/php]
[php]
<?
// home.php
$title = ‘Homepage’;
$content = ‘Welcome to the homepage!’;
include ‘skin.php’;
?>
[/php]
Post your answer if you want feedback!
HIDE_NAV is interpreted as a string value, and therefore is never false but always true. Instead:
if ( defined( 'HIDE_NAV' ) && constant( 'HIDE_NAV' ) )Actually, that was exactly backwards logic…
if ( !defined( 'HIDE_NAV' ) || !constant( 'HIDE_NAV' ) )The simple answer, “define( ‘HIDE_NAV’, false );” between lines 1 and 7 in home.php or between lines 1 and 4 in skin.php.
I’ll e-mail the more elegant design on request.
(not to mention, depending on your PHP version / distro, adding ‘php’ to the end of line 1 in each file)
Because HIDE_NAV is not defined.
Now give me a new job
Haha Jon, I’ve done that before. Given an answer then said, “I mean, the opposite!” I got a puzzled look, as if you say, “I’ll give you that–maybe.”
Phil, Dody, you’re both right. Defining the constant would fix the problem. However, I was looking for Jon’s answer. HIDE_NAV is undefined, but why is that a problem? Undefined variables get evaluated as false. Constants, however, get interpreted as strings.
BTW, a couple blatantly wrong answers would be someone scratching their head and saying, “But … HIDE_NAV isn’t defined — that should error!” Or worse yet would be someone responding, “The navigation didn’t get displayed because getNav() wasn’t defined till after it was called!
But yes, Jon hit it right on, and it would be a great chance for him to top it off with any other useful details about how strings or constants or variables work and really stand out from the rest.
For example, what does an undefined variable really equal? It’s not false. Is it null? What does isset() check? That a variable is defined or that a variable is not null? Etc.
I’ll try to post another slightly harder question in a few days!