Tools / thoughts to help with tracking variables

Hi All,

This is a bit of a general problem and maybe it’s just inexperience and I will get used to this, but I am having plenty of trouble keeping track of variable names, especially when the names are similar or are referencing external pages or a database. It becomes a bit of a jumble in my mind and I will forget what variable is needed. I have a good IDE that helps a little with this, but there must be a better way.
Do I just need more experience or is there something else that might help with this?

Sorry for the very general question up front.

Jim

Use more descriptive variable names.
Otherwise break your code down into smaller chunks and focus on those.

Personally, I like to think this is a common problem with PHP development. I’m currently using phpstorm, which does a decent job, but not all that great at trying to guess what variable you are wanting to use via intellisense. Maybe it is because I’ve done so much .NET development in Visual Studio, that I truly know how awesome it is to have that intellisense be spot on.

Part of the problem (I think), is the fact that you can write non-OOP so you have variables that span across multiple files, or if you use a view model you likely have an output routine or template where you need to put in variables that are utilized in various files. Visual Studio does an awesome job on that, and I’ve heard good things about several IDE’s (but to my knowledge none of them handle that scenario very well).

Descriptive variable names will help, but you will also start to get used to it over time. So don’t feel bad that you are constantly having to look them up between php files or whatever the scenario may be.

@jskintauy

Please supply more specific examples of name clashes.

With PHP are you setting error_level(-1); which usually detects any slight variable discrepancy?

Are you familiar with passing values/variables to a class and/or function and returning results rather than using global variables?

As far as a database is concerned then use a MVC approach. Pass a SQL statement to a MYSQL function. The result is either an object or an array. MVC can be described as requesting certain information from a third-party and getting the results in an agreed format.

Also having a config.php file of defined global constants prevents name conflicts.

Phpstorm with xdebug properly setup is great for running through your applications using breakpoints to examine the flow of everything. You can see what values are assigned to variables every step of the way and follow the application through and see how values change at each step.

I want to thank all of you for your replies.
Logic_earth made a very good reply about descriptive variables. He also caught me on something and that is that some of my code, as I look it over some of it is hard to read because I don’t use a carriage return often enough and because I don’t always separate the code in a completely logical way.

Cpadio’s reply was spot on about the difficulty I am having. I have not even begun working with OOP or frameworks. I am just past the beginner stage. That said, it seems like variables and database object names are coming from all kinds of directions from multiple includes files, functions, and from database queries / CRUD. I am having a hard time keeping the database structure clear (despite a model and the fact that I populated the database, uggh) and so I sometimes forget the row that needs to be returned. An example is how the database contains subject id, page id, form id and id. It should be easy to know which values to use, but I find myself constantly looking at where the data came from. Also, the issue of variable names rears its ugly head. I was using $result_set for a query result and then found myself using it again (I did rename that to make it more descriptive)

John_Belong’s comment about using an MVC approach for the data to simplify how you get to it sound good, but I am not there yet. Someday, I will tackle OOP and MVC but I am still at the stage where I am working on just my second project and still going through beginner / intermediate level books. I am sure it will help down the road.

aaaaarrrggh made a comment about Phpstorm and xdebug. I am using Phpstorm and feel good that I am using shortcuts and understand many basics like applying project settings, using Live Templates (advanced code snippets) and I did get xdebug to work but I don’t really know how to use it. It sounds like xdebug will help so time to learn it.

Thanks again for all the input and any future replies / suggestions.

Jim

You will love it. xDebug makes tracking bugs in your code EASY. Then there is another item, Profiler, which is just as awesome, in my opinion. I use the profiler to help identify bottlenecks in my code base, where is the execution taking the longest, how can I resolve it, or what method am I calling an outrageously number of times and is that necessary?

Definitely a nice product and I’ve just recently started to use it.

Don’t hesitate to ask questions, we all had to start somewhere and many of us are where we are today because we kept on chugging through it.

The MVC has been on the go a very long time, I believe it was IBM’s Smalltalk that introduced the concept way back in the late 1970s. Even today it is used extensively to separate the data, view and logic.

It took me some time to appreciate the MVC way of coding but as someone said “…you gotta have a plan”. MVC will no doubt manage to isolate and group the reams of code that you will be producing. It will also make it easier to “drill down” when debugging :slight_smile:

There are a vast amount of free information and a quick search produced the following:

http://www.tonymarston.net/php-mysql/model-view-controller.html

Hi Cpradio,
Yeah, I have been using xdebug a bit now. You’re right, it really helps! The profiler looks cool to and I can see how it would be valuable to tweak applications once bottlenecks are identified.

I have no doubt that MVC is a great way to plan and build these applications, based on some that I have read. Unfortunately, I still don’t have OOP concepts down. Further, I haven’t started looking at MVC frameworks (which I assume is a prerequisite) yet. Do you have some good suggestions on learning OOP? I have been using Lynda.com for some of their web classes and they have a couple courses, one on object oriented design/programming and one that looks like a survey of PHP frameworks (Codeigniter, Zend, Symfony 2, and CakePHP 2) so I guess I will start there.
I can learn from books. Do you know of a good one to get started or should I look through the free information (like the link you pointed to) and learn from the free web tutorials? Thanks ahead for your reply and your suggestion.
Thanks ahead for any advice.

Shortly after I started to learn PHP I was introduced to CodeIgniter. The latter was simple to set up, has a really good user manual, noobie friendly forum and fortunately I found quite easy to quickly expand the “Hello World” example to use a MySQL database.

OOP and MVC are both used by CodeIgniter framework but an in depth knowledge is not required when developing. Continual usage will make you appreciate the framework and become more familiar with OOP and MVC concepts.

I am not familiar with the other frameworks you mentioned but led to believe that an in depth PHP knowledge is a prerequisite.

Here’s a couple of tricks I learned early on (though not early enough perhaps) regarding databases at least:

Find a consistent naming convention for your table and column names and then stick to it.

A single table containing multiple “person” data (so make it plural).


=====
persons
=====
id
first_name
last_name
tel
.. etc

When you have a result set from mysql, lets say you picked all people with a tel no which starts with “0033”:


// use a PLURAL to describe what the set of rows actually contains
// steer clear of this result_set_12 style of anon naming...

$persons = mysql_fetch_object($sql);

// in your loop you then change the PLURAL to singular

foreach($persons as $person){

echo $person->first_name . ' ' . $person->last_name . ' Tel: ' . $person->tel;

}

Notice I also prefer to use the OBJECT notation to access the db data as it looks cleaner and is therefore easier to read, and will lead to less errors, and how you try to name your variables so that it looks a bit more like you actually saying what you are doing.

As pseudocode


for (each of the persons){
   echo the persons first name, last name and tel
}

The trick is to have a clear idea of how you are going to be accessing your code. You wont get this right from the beginning. Dont be afraid to go back and change your database.

Whereas far too often we read code on here which looks like this, where we have to scan up and down the code to find out what result set this is, and if an error has been made in choosing the field name and so on.


foreach($result_set as $row){

echo $row['field1'] . ' ' . $row['field2'] . ' Tel: ' . $row['field7'] ;

}

When you have a html form which allows an admin person to say, add a new person, use the exact same field names as your database.


<input type=text name ="first_name" />
<input type=text name ="last_name" />
<input type=text name ="tel" />

Then you will have teed yourself up to treat your code like variables, so then read loops are good, and save even more typing… top marks to you for asking such an intelligent question though, I wish I’d thought of it back when.

Wow, I am going to bookmark this thread / reply. Those naming suggestions are great. I now see that I am using some fairly descriptive names but derailing some of that goodness by calling the results with more generic names that end up being re-used. I will be immediately using your suggestion about naming database tables using a plural (which is on its face more descriptive because there are multiple items in the table…) makes it easier to name things later.
This entire thread has been very helpful to me because it has me thinking more clearly about how to name things so it allows me to have a clearer picture of how the project will work. It is already making a difference both in thinking and in starting to use xdebug to help better visualize. To me, this is a great result!

Here are a couple of useful tips:

Simple framework:
All included files are prefixed with an underscore so they easily grouped and sorted.
Toggle included files by changing 0 to 1 (false to true)



<?php /* index.php */

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<title><?php echo $title;?>
<head>
  <?php  if(0) { include '_heading-001.php';} ?>
  <?php  if(0) { include '_heading-002.php';} ?>
  <style type='text/css'>
      body {background-color:#fee}
  </style>
</head>
<body>
   <div class='container'>
      <div class='box_left'>
         <?php  if(0) { include '_box_left-001.php';} ?>
         <?php  if(0) { include '_box_left-002.php';} ?>
         <?php  if(1) { include '_box_left-003.php';} ?>
      </div>

      <div class='box_content'>
         <?php  if(0) { include '_box_content-001.php';} ?>
         <?php  if(1) { include '_box_content-002.php';} ?>
         <?php  if(0) { include '_box_content-003.php';} ?>
      </div>

      <div class='footer'>
         <?php  if(1) { include '_box_footer-001.php';} ?>
         <?php  if(0) { include '_box_footer-002.php';} ?>
         <?php  if(0) { include '_box_footer-003.php';} ?>
      </div>

    </div><?php /* container */?>
</body>
</html>


Second:
Debug function which saves typing and formatted
Works for all variables, integers, strings, object, etc
Could also use var_dump(…) instead of print_r(…);



 function fred($a) {echo "<pre>"; print_r($a); echo '</pre>';}

# usage:
  $a = array('John', 'Jack', 'Fred', ' Jimmy');
  fred( $a );
  echo __FILE__;
die;

# output formatted nicely
John
Jack
Fred
Jimmy


Saves typing and should also be in a _config.php file


 # does not produce error if already defined
 # produces shortcut for <br />'
 defined('jj') ?: define('jj', '<br />');

#usage:
  echo jj,jj,jj;


  # only requires a single file for both LOCALHOST and ONLINE
  # prevents overwriting files with same names
 defined('LOCALHOST') ?: define('LOCALHOST', 'localhost' == $_SERVER['SERVER_NAME']);

# usage:
  if(LOCALHOST)
  {
     # MySQL localhost connection details
     # show debug stuff
  }
  else
  {
     # MySQL ONLINE connection details
     # show online stuff
  }


Hi Folks,
It’s been awhile since I replied to this post. Again, it was really helpful and I have come back several times.

I wanted to pass on something that I started doing to remember the variables and the logic flow. I am using all the techniques suggested here in addition to this.
I remember one of the online classes I took that commented out all the CSS color values used in the document so they could be easily referenced. In a duh moment it occurred to me I could do the same with the PHP form and MySQL values and their associated variables. So I built a small chart for myself of the commonly used variables and put it at the beginning of my PHP / HTML file(s). It really helped me keep things straight, so I thought I would pass this idea on. Maybe all of you are way beyond this and don’t need this kind of reminder, but if not, maybe this suggestion will help.

Jim

Yep. I used to do similar.

This practice will serve you well as it in effect puts all of the important variables at the top of the script, so you (or anyone else) can see them straight off.

It is similar to what is termed “declaring variables” which is necessary in most languages (from what I understand) – the importance of which can be found by googling.

Once you delve into OOP this will become doubly important.

A natural by-product of the practice you adopted is that you then tend to try and reduce the number of variables because you become so super-concious of their existence matched with your natural tendency to want to type as little as possible, you will also start to worry about how you are polluting the global namespace, and how clashes could occur.

This again should push you towards learning more about OOP.