php basics - nogsantos/study-zce-php-certification-codes GitHub Wiki

Syntax

  • Terminate code statements with a semi-colon(;)
  • This requirement is not always strict—for example, the last instruction before a closing tag does not require a semicolon;
  • Numeros no começo da string, (ex: "12cão") ele tipa pra inteiro (ex: 12).
  • Numeros no fim ou no meio, ele converte SEMPRE pra 0.
  • Concatenação e operações de atribuição (" $a=2;") ou incremento ($a++) SEMPRE vêm antes das operações aritméticas.

A diferença entre aspas simples e aspas duplas

depende da interpretação que o php dá aos caracteres entre os sinais de aspas, antes de criar a string em si. Se incluir uma string entre aspas simples, quase nenhuma interpretação será feita. Se incluir entre aspas duplas, o php vei interpolar os valores de qualquer variável que for inclusa e fará substituições para algumas sequencias de caracteres especiais que iniciam com caracteres de barra invertidas.

Echo x Print

Ambas não são funções reais, é uma construção da linguagem. Echo, imprimir uma string com um argumento. Também pode-se fornecer diversos argumentos à versão sem parenteses de echo, separando-os por virgula echo "arg1", "arg2", "argN...";
Print, semelhante ao echo com duas diferenças importantes:

  • Diferente de echo, print aceita apenas um argumento.
  • Diferente de echo, print retorna um valor que informa se a instrução print foi bem sucedida, 1 se bem sucedida e 0 se malsucedida.

Ternary Operator

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. $a ? : 'foo'

Bitwise operator

Bitwise left shift (<<) . This operation shifts the left-hand operand’s bits to the left by a number of positions equal to the right operand,inserting unset bits in the shifted positions.
Bitwise right shift (>>) . This operation shifts the left-hand operand’s bits to the right by a number of positions equal to the right operand, inserting unset bits in the shifted positions.
It’s interesting to note that these last two operations provide an easy (and very fast) way of multiplying integers by a power of two. For example:

<?php
$x = 1;
echo $x << 1; // Outputs 2
echo $x << 2; // Outputs 4
$x = 8;
echo $x >> 1; // Outputs 4
echo $x >> 2; // Outputs 2
?>

You must, however, be aware of the fact that, even though these operations can approximate a multiplication or a division by a power of two, they are not exactly the same thing—in particular, there are overflow and underflow scenarios that can yield unexpected results. For example, on a 32-bit machine, the following will happen:

<?php
$x = 1;
echo $x << 32;
echo $x * pow (2, 32);
?>

The second line of this example actually outputs zero—because all the bits have been shifted out of the integer value. On the other hand, the second example (which calls the pow() function to elevate 2 to the power of 32) will return the correct value of simple: if either the left-hand or right-hand bit is set, the operand behaves in exactly the same as the bitwise OR. If both bits are either set or unset, the resulting bit is unset.
A third set of operators is used to shift bits left or right: 4,294,967,296—which, incidentally, will now be a float because such a number cannot be represented using a signed 32-bit integer.

A good explanation here

Breaking and Continuing

The break keyword, which we encountered briefly in the earlier section about the switch statement, can also be used to immediately exit a loop; it takes an optional parameter, which allows you to exit from multiple nested loops:

<?php
$i = 0;
while (true) {
   if ($i == 10) {
      break;
   }
   echo $i . PHP_EOL;
   $i++;
}
?>

The built-in PHP_EOL constant represents the “end of line” marker for your current operating system. Predefined Constants

<?php
for ($i = 0; $i < 10; $i++){
   for ($j = 0; $i < 3; $j++){
      if(($j+$i) % 5 == 0){
         break 2; Exit from this loop and the next one.
      }
   }
}
?>

Remember to always terminate a break statement with a semicolon if it does not have any parameters. If you do not do so and it is followed by an expression that returns an integer number, you may end up causing the interpreter to randomly exit from more than one loop—causing all sorts of difficult-to-troubleshoot situations.
There are cases in which, rather than terminating a loop, you simply want to skip over the remainder of an iteration and immediately skip over to the next. This is done with the continue statement—like with break, you can provide it an integer parameter to specify the level of nesting to which the it applies. For example, the following code will only output numbers between 0 and 3, and between 6 and 9:

<?php
for ($i = 0; $i < 10; $i++) {   
    if ($i > 3 && $i < 6) {   
        continue;   
    }   
}
?>

Handling Errors

Your scripts should always be able to recover from a trappable error—even if it’s just to advise the user that an error occurred and notify support staff of the same fact. This way, your script won’t simply capitulate when something unexpected occurs—resulting in better communication with your customers and the possible avoidance of some major problems. Luckily, error handling is very easy. Your scripts can declare a catch-all function that is called by PHP when an error condition occurs by calling the set_error_handler() function:

<?php
$oldErrorHandler = '';
function myErrorHandler ($errNo, $errStr, $errFile, $errLine, $errContext) {    
    global $oldErrorHandler;      
    logToFile("Error $errStr in $errFile at line $errLine");       
    if ($oldErrorHandler) {      
        $oldErrorHandler ($errNo, $errStr, $errFile, $errLine, $errContext);       
    }    
}   
$oldErrorHandler = set_error_handler ('myErrorHandler');
?>

As you can see, the function name of the old error handler (if any) is returned by the call to set_error_handler() —this allows you to stack several error handlers on top of each other, thus making it possible to have different functions handle different kinds of errors.
It’s important to keep in mind that your error handler will completely bypass PHP’s error mechanism—meaning that you will be responsible for handling all errors, and stopping the script’s execution if necessary.

As of PHP 5, set_error_handler() supports a second parameter that allows you to specify the types of errors that a particular handler is responsible for trapping. This parameter takes the same constant values as the error_reporting() function.

set_error_handler

Namespaces

Ex.:

<?php

set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__);
define('DS',DIRECTORY_SEPARATOR);

require_once 'MyLibrary' . DS . 'Authentication' . DS . 'Adapter.php';
require_once 'MyLibrary' . DS . 'Database' . DS . 'Adapter.php';
require_once 'ThirdPart' . DS . 'File' . DS . 'Adapter.php';

use MyLibrary\Authentication\Adapter as AuthAdapter;
use MyLibrary\Database\Adapter as DbAdapter;
use ThirdPart\File\Adapter as FileAdapter;

$authAdapter = new AuthAdapter();
$dbAdapter = new DbAdapter();
$fileAdapter = new FileAdapter();
?>