Jump to content
Larry Ullman's Book Forums

Chap 06 - Using A Variable Out Of Scope


Recommended Posts

Hello Larry,

 

First of all, I'm very glad I got your book. I'm re-learning PHP from scratch and I wished I had a book like yours in the early 2000s  ;)

 

In chapter 6, handle_reg.php, I'm a bit troubled by the variable $age

$age should only exist within "if ($_POST['year'] < 2016) {...}"

// Validate the year:
   if (is_numeric($_POST['year']) AND (strlen($_POST['year']) == 4))
   {
     // Check that they were born before 2016
     if ($_POST['year'] < 2016)
     {
       $age = 2016 - $_POST['year']; // Calculate age this year
     }
     else
     {
       print '<p class="error">Either you entered your birth year wrong or you come from the future';
       $okay = false;
     }

But still, you can call it like a global variable at the bottom of the page:

   // If there were no errors, print a success message:
   if ($okay)
   {
     print '<p>You have been successfully registered (but not really).</p>';
     print "<p>You will turn $age this year.<p>";
     print "<p>Your favorite color is a $color_type color.<p>";
   }

In another programming language, I would have defined it as a global variable at the top, then update it later on. Is it a common thing in PHP?

 

Thanks a lot for your time.

 

Cheers!

  • Upvote 1
Link to comment
Share on other sites

Thanks for the nice words! As for your question, the short answer is probably that PHP doesn't have variable scope similar to whatever languages you've learned before. More specifically, PHP doesn't have block-level scope, so the $age defined up above in the script is effectively global. (It's not actually global in the true sense b/c it wouldn't be available inside of a function, but it exists throughout the script otherwise.)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...