PHP Commands | Adrenalina

PHP Commands

Publicado Por | 11 junio , 2013 | Blog Adrenalina En | No Comments

It’s very common nowadays to use PHP in web projects and the number of persons who learn to program in this language grows with every passing day, be it by choice o by the use of blog and web creation tools like wordpress, drupal, magento, etc.

There are unknown commands or proceedings for both those who are newbies and those who worked in other languages or previous versions and which can be helpful most of the times. This post pretends to showcase some of these PHP commands.

  • “use” command

    Ever since version 5.3.0, this incorporates the so-called anonymous functions. In simple words, we could say these are functions which aren’t tied to any name (hence their name). They’ve even been added to internal PHP functions, like the array_map function. Starting with version 5.3.0, you can pass down the name of a array_map function too besides using an anonymous function. This one, like any function, has a local variable scope. Thus, the variables which aren’t global or are passed down as a parameter won’t be able to be used inside of the function.

    <?php
    $arr = array('one', 'two');
    $prefix = 'number ';
    $prefix_arr = array_map(function($val) {
    return $prefix . $val;
    }, $arr);
    var_dump($prefix_arr);
    ?>

    This code returns Undefined Variable: prefix error. In the cases like that of before, where we can’t pick the parameters the functions gets, the use instruction helps us to use variables in the function’s local ambit, even by reference:

    <?php
    $arr = array('one', 'two');
    $prefix = 'number ';
    $prefix_arr = array_map(function($val) use ($prefix) {
    return $prefix . $val;
    }, $arr);
    print_r($prefix_arr);
    ?>

    Which will return this:

    Array
    (
    [0] => number one
    [1] => number two
    )
  • Abbreviate Conditionals

    As in several programming languages, there are different manners to write something as simple as a conditional if else.

    <?php
    if (!empty($cond)) 
    {
    echo 'not empty';
    }
    else 
    {
    echo 'empty';
    }
    ?>

    equals to:

    <?php
    echo !empty($cond) ? 'not empty' : 'empty';
    ?>

    Besides, to carry out conditional assignments, we can also play with the operators AND and OR (or && & ||), knowing that, php, span style=”text-decoration: underline”>doesn’t evaluate a full condition if the parts processed ‘till now return a safe result (in true OR $c and in false AND $c, the variable $c isn’t processed.)

    <?php
    if (!empty($cond)) 
    {
    $a = 'not empty';
    }
    else 
    {
    $a = 'empty';
    }
    ?>

    equals to:

    <?php
    !empty($cond) 
    and $a = 'not empty'
    or $a = 'empty';
    ?>
  • Show array content by parts

    Sometimes, when dynamically generating HTML content in a vista from data exported from a database, like, when showing array content by parts to split it into different files. The array_chunk function can help us:

    <?php
    $datos = array('one', 'two', 'three', 'four', 'five');
    $filas = array_chunk($data, 3);
    echo '<table>';
    foreach ($files as $file) {
    echo '<tr>';
    foreach ($file as $column) {
    echo '<td>' . $column . '</td>';
    }
    echo '</tr>';
    }
    echo '</table>';
    ?>

    Will generate:

    <table>
    <tr>
    <td>one</td>
    <td>two</td>
    <td>three</td>
    </tr>
    <tr>
    <td>four</td>
    <td>five</td>
    </tr>
    </table>
  • Capturing exceptions & errors

    For a better alternate flux control in our programs it’s very recommended to make use of exceptions. Even while trying to always capture the exceptions, there can be times in which these aren’t gathered by a catch block: this will make PHP show the error or generate an error 500. There are 2 functions to globally capture what to do when a non captured exceptions jumps out or an error is triggered. This will allow us to manage these mistakes, be it storing them in a log before ending the page execution or showing relevant info to the user, cancelling database transactions or even redirect to an error page.

    <?php
    set_exception_handler(function($exception) {
    echo $exception->getMessage();
    });
    set_error_handler(function($errno, $errstr, $errfile = null, $errline = null) {
    echo 'Error ocurred: [' . $errno . '] ' . $errstr . '(' . $errfile . ' - ' . $errline . ')');
    });
    ?>
  • Parse a conf. file

    There are different standard formats for the conf. files. We can have conf. values in an array with keys in a php file, a conf xml file, etc. Another form is to create an .ini file with the same format used by php.ini. To pick up the values we can use the function parse_ini_file. This will return an array with all propierties stored in the file using the format key =gt; value. Using the second parameter set to true we could even gather different sections.

    ; .ini file example
    ; comments using ";" won't be included in the returned array
    [first_section]
    route = "/usr/local"
    project = "php"
    [second_section]
    version = 2
    <?php
    $ini_props = parse_ini_file('archivo.ini', true);
    print_r($ini_props);
    ?>

    which will display:

    Array
    (
    [first_section] => Array
    (
    [route] => /usr/local
    [project] => php
    )
    [second_section] => Array
    (
    [version] => 2
    )
    )
  • Classes Auto-load

    Very common in development frameworks: classes auto-load, which allows to automatically include the files which have the classes when you gotta use them . This is beneficial ‘cause we won’t have to add a list of require or include with all of our files. We also make sure that only the files we need of are loaded into the page.

    If we don’t use any framework, or ours doesn’t allow for that, we can develop it ourselves using the php function spl_autoload_register. Example: the following code will automatically load the files of the classes with the name as in class.php, accessible from the include_path:

    spl_autoload_register(function ($class) {
    require_once $class . '.class.php';
    })

    The function spl_autoload_register adds the indicated function to the auto-load queue. We can have more than one function in the queue to verify different criteria which will be executed one after the other until the file is found or there’ll be an error if no function finds them. You can include code to check that the file exists (using function file_exists).

    If our files are organized in a directory tree, we can define some directives or conventions to easily find the class files. Example: define class Core_Utils_Func is found on the route /Core/Utils/Func.php. We can also use the namespace to define the routes to the files.

Autor: mauro flores

Estudiamos y analizamos su negocio en profundidad, definimos objetivos y planteamos la estrategia de marketing más adecuada centrándonos en conseguir cada uno de los objetivos propuestos. Solicita Presupuesto Ahora

Uso de cookies

En este sitio web utilizamos cookies propias y de terceros para mejorar nuestros servicios, para que usted tenga la mejor experiencia de usuario y analizar su visita. Si continúa navegando está dando su consentimiento para la aceptación de las mencionadas cookies y la aceptación de nuestra política de cookies, pinche el enlace para mayor información.