Some more interesting features.

    Inspired by past favorite topics .

    In php, as in any language, there are constructions that for one reason or another have not found wide application, however, knowledge of such non-standard techniques can sometimes make your life easier. Today I will talk about one such opportunity. The article is designed for novice programmers and just curious people.

    Everyone (I hope) knows the wonderful __autoload function whose advantages are appreciated by those who switched to php 5. But even earlier, back in 4-ke, one could find constructions of the form:

    function init ($ cname) {
      if (! class_exists ($ cname)) {
        require $ cname. '. inc.php';
      }
    }

    init ('myClass');
    $ a = new myClass;

    Now you will not meet this, but the opportunity remains. And it’s a sin not to use it.

    And the possibility lies in the fact that you can declare classes and functions inside other language constructions .

    The following are examples of functions, but all of the following is true for classes.

    Consider one example. You have a function whose logic depends on some difficult condition that does not change ( ! ) In the process of the script. For example, the logic depends on the selection from the database. The classic solution looks like this:

    if (/ * severe condition * /) {
      define ('MYCONST', true);
    } else {
      define ('MYCONST', false);
    }

    function my_func () {
      if (MYCONST) {
        // code
      } else {
        // different code
      }
    }

    We had to introduce an additional constant, and smart little Pinocchio people know that to produce essences is evil. However, knowing the ability to wrap declarations in a construct, you can rewrite this code as follows:

    if (/ * severe condition * /) {
      function my_func () {
        // code
      }
    } else {
      function my_func () {
        // different code
      }
    }

    Agree, it looks nicer? :)

    The idea ends here and the fantasy begins. Everyone can dream up :) I’ll offer one more example that uses the fact that in php a function declared once becomes globally accessible .

    Example:

    function a () {
      if (! function_exists ('b')) {
        function b () {
          if (! function_exists ('c')) {
            function c () {
              return "Three";
            }
          }
          return "Two";
        }
      }
      return "One";
    }

    echo a ();
    echo b ();
    echo c ();

    It is easy to guess that these three functions can only be called in this order . It can be useful with all kinds of initializations, etc.

    I will make a reservation once again, these constructions are rather exotic and you may never have to use them in practice, but you still need to know about such language features. At least for general development;)

    PS: All code kindly highlighted Source Code Highlighter .

    Also popular now: