Jump to content

Simple variable initialization question


doug

Recommended Posts

In the "PHP Programming" book I'm reading, there is the following working example:

<?phpfunction count_list() {   if(func_num_args() == 0) {     return false;   }   else {     for($i = 0; $i < func_num_args(); $i++) {       $count += func_get_arg($i);     }     return $count;   } } echo count_list(1, 5, 9);?>

Something similar in JavaScript would cause an error at the $count += statement because it had not been initialized.Is this considered ok programming practice in PHP - to not initialize variables before you start to += to them?doug

Link to comment
Share on other sites

In PHP, it will cause a notice, but it will work non the less. It's a good programming practice to initialize variables before using an "operator=" on them, but not doing so isn't an error.

Link to comment
Share on other sites

I dislike even the slightest form of error, warning, notice, casual suggestion etc. AND my gut simply rejects the assumption that an uninitialized variable = 0. Especially in a language that hawks and spits when you test an unititialized array against false. (Which is why we have all those isset and empty tests.) In any case, I'm accustomed to initializing variables, so in your case, Doug, I too would set $count to zero before I started incrementing it.

Link to comment
Share on other sites

Is this considered ok programming practice in PHP
It's not OK to do that, but a lot of people do because they don't know any better and when they run it "it works". If you add this code to the top of the page you will see the error message. It's a good idea to use this code on all of your development pages to make sure there aren't even any notices, it just produces better, more efficient code.ini_set("display_errors", 1);error_reporting(E_ALL);If you're developing a large project, it's common to have 1 include file that everything else includes to initialize everything, like a config file. In a project I'm working on now I use this for my config file:
<?phpif (version_compare('5', PHP_VERSION, '>')){  echo 'This application requires PHP version 5 or later.';  exit();}if (!function_exists('json_encode')){  echo 'This application requires support for the json_encode function inside PHP.';  exit(); }error_reporting(E_ALL);ini_set('error_log', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'error.log');ini_set('html_errors', 0);ini_set('log_errors', 1);ini_set('display_errors', 0);require_once 'global.config.php';require_once 'class.db.php';$db = new tc_lms_database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);require_once 'class.session.php';$sess = new tc_lms_session();require_once 'class.userfield.php';require_once 'class.userfields.php';$uf = new tc_lms_userfields();?>

So every single one of the files in my application includes that file. From the top, first it checks to make sure the server is running PHP 5 or later, my application won't run on PHP 4. The next part makes sure that the json_encode function exists. Eventually I'll take that out and instead of quitting it will just define the function if it doesn't exist already. The next block sets all of my error preferences, so it disables HTML errors and on-screen errors and instead uses an error log file to store all of the errors. That is the best setup for live applications because you don't want to users seeing all your error messages, but you will want them recorded. Using an error log preserves the specific error message with the file, line number, time and date for later debugging. In this case it's necessary because my application does a lot of AJAX work so I wouldn't even see an error message if the AJAX script printed one, so I have to store them in an error log. The rest of the file includes some other required files and initializes a few objects (database object, session object, etc). Since this file is used by every other file in the application, changing those error settings will affect every page.

Link to comment
Share on other sites

It's not OK to do that, but a lot of people do because they don't know any better and when they run it "it works". If you add this code to the top of the page you will see the error message. It's a good idea to use this code on all of your development pages to make sure there aren't even any notices, it just produces better, more efficient code....So every single one of the files in my application includes that file.
Speaking of including things on every page - do people tend to build an entire library of functions that are loaded on every page regardless of whether they are used on that page or not? Or do people tend to build sets of library functions that are loaded on different pages according to use?One thing about PHP that is different from the server-side JavaScript I've been using is that I had a bunch of huge source files that were compiled once and could then be used anywhere. But with PHP everything gets re-parsed and then interpreted for every single page that is loaded, right? I'm amazed that this isn't an overwhelming burden on the server.doug
Link to comment
Share on other sites

Yeah that's correct. PHP is pretty fast about it, the interpreter is written in C. But yeah, it will load everything on every page load. If you want to see what kind of effect that has on your application you can use these functions to watch what's going on with memory:http://www.php.net/manual/en/function.memory-get-usage.phphttp://www.php.net/manual/en/function.memo...-peak-usage.phpThe default memory limit for a PHP script was 8MB prior to 5.2, 16MB in 5.2, and 128MB after 5.2.

Link to comment
Share on other sites

Yeah that's correct. PHP is pretty fast about it, the interpreter is written in C. But yeah, it will load everything on every page load. If you want to see what kind of effect that has on your application you can use these functions to watch what's going on with memory:http://www.php.net/manual/en/function.memory-get-usage.phphttp://www.php.net/manual/en/function.memo...-peak-usage.phpThe default memory limit for a PHP script was 8MB prior to 5.2, 16MB in 5.2, and 128MB after 5.2.
I'll check those out, thanks. I was more worried about speed than memory. How does a place like Facebook deal with that? Do they use a special "compiled once" version of PHP or is it the same PHP that everybody else uses? Do they just serve off of a zillion servers?doug
Link to comment
Share on other sites

It's probably just more servers. There are products like Zend Optimizer that can help speed up PHP code but to my knowledge you can't compile it. If you want to track time, you can use the microtime function to record the start time and then at the end of the script get the difference between that and the current time to see how long the script took. But considering how many libraries PHP itself needs to load to even run, I doubt that including a bunch of external scripts is going to cause much of a dent.

Link to comment
Share on other sites

It's probably just more servers. There are products like Zend Optimizer that can help speed up PHP code but to my knowledge you can't compile it. If you want to track time, you can use the microtime function to record the start time and then at the end of the script get the difference between that and the current time to see how long the script took. But considering how many libraries PHP itself needs to load to even run, I doubt that including a bunch of external scripts is going to cause much of a dent.
It's impressive that it works as well as it does as an interpreted language that needs to "start from scratch" basically for each page that is loaded!doug
Link to comment
Share on other sites

Yeah definately, in college we were taught that all interpreted languages are inherently slower then compiled languages. But they've obviously put a lot of optimization into the C code, and it also doesn't hurt that CPU power and memory is so inexpensive.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...