0

In some examples of PHP, I see people assign things to shorthand variables, and then use the shorthand variables instead. Is this common practice? Is this good practice?

$name = $_POST['name'];

and then they use they use $name down here to echo it or use it as a function parameter.

Another example is:

DEFINE('DB_USER', 'username');
mysqli_connect(DB_USER.......);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
Caleb
  • 135
  • 2
  • 10
  • 1
    Yep, perfectly normal. – Niels Keurentjes Dec 29 '13 at 01:29
  • 1
    There is a constant, not variable in the second example – Your Common Sense Dec 29 '13 at 01:30
  • Why don't people just use it directly rather than assigning it to another variable? – Caleb Dec 29 '13 at 01:30
  • Sorry about that, I am asking why people choose to do this rather than use values directly, but I didn't know how to ask it. Variables and constants! – Caleb Dec 29 '13 at 01:32
  • Personally, `$name = $_POST['name']` is a no-no because you are making a "copy" of something that already exists. However, `DEFINE('DB_USER', 'username')` is perfect as this is a constant that should be defined once (on a separate PHP script) and included in the PHP when needed (with `require_once('name of script with constants')`. This also allows for a quick `username` or `password` change in one spot only. – Tigger Dec 29 '13 at 01:32
  • possible duplicate of [Is it preferred to assign POST variable to an actual variable?](http://stackoverflow.com/questions/9049736/is-it-preferred-to-assign-post-variable-to-an-actual-variable) – some Dec 29 '13 at 03:43
  • @Tigger I disagree with you. Using `$name = $_POST['name']` is my preferred way, because if I need to change `$_POST` to `$_GET` I only need to change it in one place. Actually I am using a function that checks the length and optionally type. With `$name = $_POST['name']` it is only a pointer that gets copied once, after that you save 9 bytes of source code every time you use the variable or 12 if you use `$_REQUEST`. It could also save some CPU-cycles since it doesn't need to search the array every time it is used. In this case it isn't that expensive, but in jquery `$('#name')` is. – some Dec 29 '13 at 04:22

3 Answers3

3

Pros:

  • Shorthand variables can be easier to type and remember.
  • A shorthand variable might allow an expensive operation to be done once instead of repeated many times. But beware of premature optimization! Most of the time this sort of optimization would be premature.
  • A shorthand variable can be used to make a copy that can be changed without modifying the original variable.
  • In some languages, a shorthand variable can be used to make a copy that is guaranteed to persist even if the the original variable is modified.

Cons:

  • Indiscriminate use of shorthand variables can result in multiple names for the same values.
  • In some languages and situations, a shorthand variable will make an unnecessary copy, using additional resources.
Monica For CEO
  • 499
  • 6
  • 20
2

I have been doing php professionally for about 5 years now.

Usually when getting post variables it is a good idea, but even more common is to wrap it in an isset ternary if statement:

$name = isset($_POST['name']) ? $_POST['name'] : false;

This way if the variable isn't passed then you don't get an undefined variable warning.

Further, it saves you having to type $_POST every time, and it helps encapsulate the code a bit better.

ddoor
  • 5,819
  • 9
  • 34
  • 41
  • is it wasteful, in that you are creating a copy of data? – Caleb Dec 29 '13 at 01:40
  • Does it copy the memory though? – ddoor Dec 29 '13 at 01:42
  • php stores a pointer to the data inside the $_POST variable when you assign it to name. I know php doesn't give you access to pointers but under the hood it does. Check "tim"'s answer to this post: http://stackoverflow.com/questions/9049736/is-it-preferred-to-assign-post-variable-to-an-actual-variable – ddoor Dec 29 '13 at 01:45
  • I'd rather use null than false to indicate that the variable has not been set. true/false should be used for boolean variables. – demux Dec 29 '13 at 01:55
  • you can use whatever you want there. Depends how your code works. – ddoor Dec 29 '13 at 04:44
  • @FaddishWorm Fix me if I misunderstood your point, but you think after `$name = $_POST['name'];` there is no copy operation in memory and `$name` pointers to the same data as `$_POST['name']`? – Alexander Yancharuk Dec 29 '13 at 07:48
1

The most important thing when writing code is writing readable code, not just for others but also for yourself. We do this all the time, i.e. abstracting and applying oo methods of programming.
So predefining the variables we'll be using and setting defaults makes perfect sense.

I would do something like this...

class ValueTooLong extends Exception {}

function R($param, $default=null, $type='string', $max_length=null) {
    if(!isset($_REQUEST[$param]))
        return $default;
    $r = $_REQUEST[$param];
    if($max_length && strlen($r) > $max_length)
        throw new ValueTooLong('Length of '.$param.' was '.strlen($r).'. Max length is: '.$max_length);
    if($type === 'bool' || $type === 'boolean') {
        if($r === 'false' || $r === 'no')
            return false;
        return !empty($r);
    }
    settype($r, $type);
    return $r;
}

# Which allows me do do this:
$name = R('name');
# or:
$count = R('count', 1, 'int');

EDIT: Function now takes a max_length parameter (as suggested by comment) and throws an exception if value of request parameter is too long

demux
  • 4,544
  • 2
  • 32
  • 56
  • 1
    I always use a function that copy the value to a new variable after it has checked that the original has the right length (don't you just hate it when you get a 5MB when expecting 20 bytes?) and optionally the type. – some Dec 29 '13 at 03:41