Why define a constant for the same document and check if it exists in the document itself?

Asked

Viewed 101 times

2

I see in many codes out there programmers that setam a constant and in the document itself check whether this constant exists (was defined) in itself. I would like to know why this happens.

When we download open source from the forum platform phpBB3, and open the file install/database_update.php, right in the first lines we notice this:

if (defined('IN_PHPBB') && defined('IN_INSTALL'))
{
    $updates_to_version = UPDATES_TO_VERSION;
    $debug_from_version = DEBUG_FROM_VERSION;
    $oldest_from_version = OLDEST_FROM_VERSION;

    return;
}

define('IN_PHPBB', true);
define('IN_INSTALL', true);

In almost all files found for download in the code of phpBB3, there is this constant define('IN_PHPBB', true); being defined at the beginning of the code.

This is the main example I can remember to clarify my doubt.

Based on this code (and some others I’ve seen around, but I won’t have a hand), is there any particular reason for this? It’s some kind of good safety practice?

  • I would say that if the define and the if are in the same file does not make much sense. But when we have "includes" and those lines are in different files then it is good practice. Take a look at a similar question: http://answall.com/q/43650/129

  • You could link some examples to show a context.

  • @bigown, I have "at hand" here just the example of phpBB3, although I have seen it elsewhere.. I tried to elucidate my question better.

1 answer

1


It is difficult to say for sure what the intention of third parties is if they have no documentation. An accurate answer could only be given by the person who did it. I can tell you why I would do something like this... if I did it or because I think I would have it in a code.

Defensive programming

It may sound strange, but what if one day parts of the code are separated, who will realize that they need to verify the existence? It is the same principle of using keys even on blocks of a line. The day you need to increase a line need not worry.

Extensions

A variation of the first reason. In this case PHPBB is a software known to have an extension system that often changes the main source code. So it makes sense to check why an extension might create some problem.

Bequest

It was in two sources and they were merged and would not have to refactor too much. It was easier to leave so. This happens especially when several programmers work in the same code. This may even have happened because a source was created by code generator and then merged. It is a less likely chance in the possible.

The programmer is lost

I never rule out this possibility. But I always get the first and second with the second.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.