Jump to content
Larry Ullman's Book Forums

Question Regardin The Initialization Of Variables


Recommended Posts

Chapter 4 - the basics - initialize variables prior using them.

 

When using a form I tend not to initialize the variables before the "if form submitted" condition. Instead after the form is submitted when comes the validation section i do something like this:

 

$var = (!empty($_POST['var'])) ? $_POST['var'] : (bool) FALSE;

 

This way I avoid to initiate variables as far as the form is not submitted and I do not need them. Also I found the code easier or at least shorter. Is this wrong or dangerous?

Link to comment
Share on other sites

Sorry, it is PHP5 Advanced the book that I had in mind. Is it possible to move the post to that forum? The question is still valid and probably applies to any of your books as it is about initializing the variables. If I do not use them until the form is submitted, isn't better not to initialize them until than? Basically I would like to initialize the variables only when the form is submitted and I found this syntax short.

Link to comment
Share on other sites

It's just bad coding style. To keep code short is generally a very good idea. Simple solutions to difficult problems is always good, but readability is even more important. If you like short code, create several functions that keeps your code simple.

 

The real problem here, however, is type. You should not return value OR a boolean. They are not the same type. Return value or null, and true or false. This will in the end give you code that is much easier to read and predict. Create your own functions for validating vital input. Good function names are very important to ensure that your code is easy to understand and use.

 

(The do_some_calculations_on_integer() function is not a good name btw :P )

 

Basically I would like to initialize the variables only when the form is submitted and I found this syntax short.

 

As explained in my code, you should first check that $_POST is even set. (form is sendt). $_POST is an array, so we can use isset() to se if the post ARRAY is set. This is also the way Larry says you should do it in his books.

 

// Check that script is even sending post before anything
if ( isset($_POST) )
{
  $integer = $_POST['val'];

  if ( valid_integer($integer) )
  {
  echo 'Input is an integer. ';

  // Calculate the value according to a method.
  $new_value = do_some_calculations_on_integer( $int );

   // We check that function did not return null
  if ( $new_value != null )
  {
	   echo $new_value; // Value is ok! Put in database or whatever
  }

  }
  else {
  echo 'Input is not an integer.';
  }

}

function valid_integer( $int )
{
return ( ctype_digit( (string) $int ) && is_int( (int) $int ) ) ? true : false;
}

function do_some_calculations_on_integer( $int )
{
   // This is the validation of input, if needed. I have just said that the $int argument should be between 1 and 9.
   // You will of course replace this what what you need. (Maybe you can skip the whole validation? It depends.)
if ( 0 < $int < 10 )
{
	// Some random calculations. This is to illustrate that you can manipulate value inside a function instead of in code.
	$exponent = pow($int, 3);
	$devision = $exponent / 2;
	$pi_multiplcate =  $exponent * pi();
	return (int) $pi_multiplcate + 42;
}
else
{
  // We only allow values between 1-9 allow for some reason. Value is not what we wanted.
  // We indicate this by null or some other value that CAN'T be right. (-1 is an option if we only want positive numbers)
  return null;
}

}

  • Upvote 1
Link to comment
Share on other sites

In the book I've seen that after we check if the form is submitted we assume all values FALSE. Than we perform validation and if validation is passed we take the value. (pag 500, PHP6 and MySQL5). Than it comes a conditional to check if all required variables have a value. What I did was simply to take out the first statement where we assume all values as being FALSE and write it in shortly manner with the ternary operator.

 

What you are saying it makes sense and I understand your reasons, but PHP is not a strongly typed language and readability it's not a problem in this case as in fact I found it more readable this way.

 

The examples are something like this:

 

 

$fn = $ln = (bool) FALSE;

 

// validation ommited

 

$fn = $_POST['fn'];

$ln = $_POST['ln'];

 

if ($fn & $ln) {

// do something

}

 

How would you re-write it following your advise to keep the datatype of the same type?

Thank you for your reply.

Link to comment
Share on other sites

  • 2 weeks later...

The variables are only regarded as false because of how if() works. The variables are really 'null' (empty) and thus the code if ( $var ) will be false. This would also be the case without instantiating the variables, but you would also get the php error "undefined variable" in your scripts.

 

You will more often see Larry checking if an error array is empty (code run without error) than checking a specific variable. It does not make sense to use the value of a variable OR set the variable to true/false.

 

$error_array = array();

 

$firstname = $_POST['firstname'];

 

// check VALUE of $firstname

If ( strlen($firstname) < 2 ) {

// firstname IS under 2 chars long. Define an error

$error_array[] = "Firstname must be at least 2 characters long";

}

 

// error array will be empty if no errors exist

If ( empty($error_error) ) {

echo $firstname . ' is over 2 chars long! Yay';

} else {

Echo $errors_array[0];

}

 

I'm sorry, but I write on mobile. Hope this was clear enough. :)

 

Link to comment
Share on other sites

Thank you for your reply. I understand your point of view and I agree that it makes sense and it is better. The only problem I see with this approach with the "error" array is that you cannot place the error messages next to the form field that did not passed the validation. Any thoughts? I guess a javascript/ajax validation before the server validation done as "error" array model is the best solution. Will you go for something else?

 

Regarding another post I begin to understand the advantages of OOP. I have a question regarding the creation of an add function that will add to database using prepared statements and having variable bind parameters. I believe you already worked this out and you probably have a CRUD class, will you be so kind to answer that thread? Thank you again.

Link to comment
Share on other sites

Yes you can. Take my previous code. You may assign the error message to an assosiative array like so:

 

$error_array = array();

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];

// check firstname
If ( strlen($firstname) < 2 ) {
  $error_array['firstname'] = "Firstname must be at least 2 characters long";
}
// Check lastname
If ( strlen($lastname) < 3 ) {
  $error_array['lastname'] = "Lastname must be at least 3 characters long";
}

// We are now in the html form

<input name="firstname" type="text" />
<p class="error"><?php if ( isset($error_array['firstname']) ) echo $error_array['firstname']; ?></p>

<input name="lastname" type="text" />
<p class="error"><?php if ( isset($error_array['lastname']) ) echo $error_array['lastname']; ?></p>

 

:)

Link to comment
Share on other sites

 Share

×
×
  • Create New...