Wednesday, March 9, 2016

Useful PHP Tips Revisited Link Final Day

9. Use the Suppression Operator Correctly Link

Always try to avoid using the error suppression operator. In the previous article, the author states:
The @ operator is rather slow and can be costly if you need to write code with performance in mind.
Error suppression is slow. This is because PHP dynamically changes error_reporting to 0 before executing the suppressed statement, then immediately changes it back. This is expensive.
Worse, using the error suppression operator makes it difficult to track down the root cause of a problem.
The previous article uses the following example to support the practice of assigning a variable by reference when it is unknown if $albus is set:
<?php
$albert =& $albus;
?>
Although this works — for now — relying on strange, undocumented behavior without a very good understanding of why it works is a good way to introduce bugs. Because $albert is assigned to $albus by reference, future modifications to $albus will also modify $albert.
A much better solution is to use isset(), with braces:
<?php
if (!isset($albus)) {
$albert = NULL;
}
?>
Assigning $albert to NULL is the same as assigning it to a nonexistent reference, but being explicit greatly improves the clarity of the code and avoids the referential relationship between the two variables.
If you inherit code that uses the error suppression operator excessively, we’ve got a bonus tip for you. There is a new PECL extension called Scream that disables error suppression.
Further more details:

  • PHP TRAINING IN KATHMANDU
  • PHP TRAINING IN LALITPUR
  • 10. Use isset() Instead of strlen() Link

    This is actually a neat trick, although the previous article completely fails to explain it. Here is the missing example:
    <?php
    if (isset($username[5])) {
    // The username is at least six characters long.
    }
    ?>
    When you treat strings as arrays, each character in the string is an element in the array. By determining whether a particular element exists, you can determine whether the string is at least that many characters long. (Note that the first character is element 0, so $username[5] is the sixth character in $username.)
    The reason this is slightly faster than strlen() is complicated. The simple explanation is that strlen() is a function, and isset() is a language construct. Generally speaking, calling a function is more expensive than using a language construct.

    No comments:

    Post a Comment