8 things you can do with PHP

8 things you can do with PHP

PHP is a very powerful language, commonly sub-estimated by some web developers. It is fast to code; there are many frameworks you can use; it is very easy to host.

In this article I try to demonstrate some tricks using PHP. Some of them can be very useful, while others are just "because you can". So, lets code!

1. Boolean result with switch statements

All PHP developer uses Switch Statement from the variable to the possible results.

switch ($x) {
  case 'a' : echo 'You choose the A item'; break;
  case 'b' : echo 'You choose the B item'; break;
}

But you can do the same thing but in a different way:

switch (true) {
  case ($x == 'a') : echo 'You choose the A item'; break;
  case ($x == 'b') : echo 'You choose the B item'; break;
}

Really cool ah!

Thinking that for a moment... this code makes sense if you think from the result first to the proposition. But if you have a situation like a bellow:

<?php
$x = 5;
switch (true) {
  case ($x == 5) : echo 'The variable is Five!'; break;
  case ($x == 6) : echo 'You will not see this message!'; break;
  case ($x > 2) : echo 'The variable also grater than two'; break;
}

Here, you will get only "The variable is five". But what about the other case, $x is really greater than two. Because you have the "break" command at the end of the line, the switch statement close after the first assert. Because the behavior of switch in PHP, if you remove the "break" command the language continue to the next line, independently if it is true or false. So, this trick will get only the first assert.

2. Variables from variables

Do you know that a variable in PHP can have a variable name? weird ah!

Let me explain better. In PHP, you can have a variable to call another variable. See the example below:

$name = 'box';
$stuf = 'name';

echo $stuf.'<br>';
echo $$stuf.'<br>';

/*
The result will be:
name
box
*/

Feel the power? now, imagine a simple situation on this next example:

class MyObject { 
    var $field = 'foo';
} 

$obj1 = new MyObject; 
$obj2 = 'obj1';

echo $$obj2->field; 

/*
You will get:
foo
*/

In this code above, you initialize the object MyObject on $obj1. $obj2 receives a string with the same name of the variable $obj1. Using the variable variable, you can access the class MyObject from a string variable.

Just to clarify:

$name = 'box';
$stuf = 'name';
$table = 'stuf';

echo $table.'<br>';
echo $$table.'<br>';
echo $$$table.'<br>';

/*
This works too. You will get:
stuf
name
box
*/

3. You can enable/disable/manipulate error reporting

When you go into production, you can switch off the error reporting. But, beyond this, you can catch all the messages and put in a file or send by email to the developer team.

// Disable all the error reporting
error_reporting(0);

// Enabled all the error reporting
error_reporting(1);

Now is the best part, catch all the messages:

set_error_handler( 'ManageErrors' );

// Define your own error reporting manipulator
function ManageErrors($errno, $errstr='', $errfile='', $errline='') {

  // Constants related to the $errno parameter
  $errorType = array (
    E_ERROR => 'ERROR',
    E_WARNING => 'WARNING',
    E_PARSE => 'PARSING ERROR',
    E_NOTICE => 'NOTICE',
    E_CORE_ERROR => 'CORE ERROR',
    E_CORE_WARNING => 'CORE WARNING',
    E_COMPILE_ERROR => 'COMPILE ERROR',
    E_COMPILE_WARNING => 'COMPILE WARNING',
    E_USER_ERROR => 'USER ERROR',
    E_USER_WARNING => 'USER WARNING',
    E_USER_NOTICE => 'USER NOTICE',
    E_STRICT => 'STRICT NOTICE',
    E_RECOVERABLE_ERROR => 'RECOVERABLE ERROR'
  );

  // If it was a knowed error or a generic exception
  if ( array_key_exists( $errno, $errorType ) ) {
    $err = $errorType[ $errno ];
  } else {
    $err = 'CAUGHT EXCEPTION';
  }

  // Different treatments for different errors
  switch ($err) {
    ...
    ...
  }
}

4. You don't need to close the PHP tag anymore.

On PHP, you need to start your code with "<?php" and close with "?>". But if you work with a full php file, you don't need to use "?>" the end of the file. In fact, you really should not to use it. If you close your code with "?>" and add a space after, you can face some problems if you are working with many includes.

5. Comment your code!

All serious developer should comment his own code. Because? because you need it.

Suppose you create a simple function today and return to this same function in two or three years. You will don't remember what this function does. So, insert a comment trying to tell to yourself why you did that function and how it works. This can help you and all your team.

In my experience, a good way to comment a function for example:

function ConvertCurrency(String currency, Float number)
{
  /**
  Convert a number to another currency

  :param String currency:
    The currency ISO Name you want to convert to

  :param Float number:
    The number you want to convert

  :return Float:
    The number already converted
  */

  ...
}

Make sure about the type of your variable.

This is another important rule. See the code bellow:

$x = $_GET['x'];
if ($x == '5') {
    echo 'Yes, it is five';
}
if ($x == 5) {
    echo 'Yes, it is five';
}
if ($x === 5) {
    echo 'No, the variable is a string, not a number';
}

The PHP language tries to help you with the types. A number can be represented by a number or a string. But it is a danger. See this situation:

$v = $array('apple' = 'fruit', 'table' => 'wood');
if (array_key_exists('apple')) {
    echo 'Found it';
}

This code is a trick. All Array in PHP starts on the zero position. So, the index 'apple' is on the zero position. In Boolean, zero is false. To avoid this, you should use:

$v = $array('apple' = 'fruit', 'table' => 'wood');
if (array_key_exists('apple') !== false) {
    echo 'Found it';
}

As you can see, "!==" means that you is comparing the value and the type of the variables. So, "array_key_exists('apple')" will return "0", but a number, not a Boolean.

7. Quotes and double quotes.

In PHP you have two ways to declare a string.

$x = 'abc';
$y = "abc";

Simple Quote is just a string. Double Quote, however, can accept commands. In the example above, $x and $y apparently have the same value. However...

$a = 'c';
$x = 'ab$a';
$y = "ab$a";

See the difference? $x will be equal to 'ab$a' but $y will be 'abc'. So, for string, try to use a simple quote only.

Another advantage, you think in optimization, the Single Quote is a bit faster than Double Quote because the PHP will not try to process any variable inside that string.

8. Manipulate the output buffer

This is one of the coolest thing here. PHP can manipulate the out buffer, releasing the content to the front-end in parts.

See a little example:

for ($i = 0; $i < 10; $i++) {
    echo $i;
    ob_flush;
    flush;
    sleep(1);
}

The code above print numbers on the page just when the echo command demands. In resume, you can deliver contents to the front-end while your back-end is processing. This is very useful for optimizations. Imagine building a page with a big javascript code at the end of the body. You can deliver a banner on the top of the page just before the body content. While the user is seen the banner, the rest of the body is loaded. This makes your site very fast because you don't need to wait for the PHP file processing finish, sending the content to the user in parts, replicating the user experience. What is the advantage to load the footer if your visitor is on the top of the page yet?

To manipulate your output, you can do something like this:

function Manipulate($buffer) {
    $buffer = replace('Angelo', 'Henrique Angelo', $buffer);
    return ($buffer);
}

// Clear all possible output until here
ob_clean();

// Start the buffer
ob_start('Manipulate');

// this echo is on the buffer yet
echo 'My name is Angelo';

// Release the buffer to the front-end
ob_flush;

Whit this example below, your output will be 'My name is Henrique Angelo'. Suppose you need to validate all output content in a PHP script that generates an excel file and you want to put copyright at this same file. By this trick, you don't need to worry about it by checking your code and verify if you put that copyright. Leave the system do this for you.

An important thing here, when you start the buffer, you cannot send the content to the front-end until your PHP script is finished. You want to send a content during your script, you cannot start the buffer.

Conclusion

Here I try to demonstrate some stuff I learned with my PHP experience in my work and with some friends and work colleges. If you want to share new tips os if you want to comment anything that I put here, feel free to contribute.

To view or add a comment, sign in

More articles by Henrique Angelo P.

Others also viewed

Explore content categories