php [Docs]

User Tools

Site Tools



PHP: server side scripting language. PHP is a flexible, dynamic language that supports a variety of programming techniques. It has evolved dramatically over the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in PHP 5.3 (2009), and traits in PHP 5.4 (2012).

Functional Programming PHP supports first-class functions, meaning that a function can be assigned to a variable.

Exceptions (PHP 7)

The best code controls all the posible exceptions and ensure that the code doesnt break.

In the previous versions of PHP, there was no way to handle fatal errors in your code Handling fatal errors in the past has been next to impossible in PHP, could simply halt script execution. Now, in PHP7 when a fatal or recoverable fatal error (E_ERROR and E_RECOVERABLE_ERROR) occurs a special exception will be thrown, rather than halting a script:

In PHP 7, an exception will be thrown when a fatal and recoverable error (E_ERROR and E_RECOVERABLE_ERROR) occurs, rather than halting script execution Exceptions thrown from fatal and recoverable errors are instances of a new and separate exception class: Error To unite the two exception branches, Exception and Error both implement a new interface, Throwable.

interface Throwable
    |- Exception implements Throwable
    |- Error implements Throwable
        |- TypeError, ParseError, ArithmeticError, AssertionError 
  • Class throwable: Exception an Error.
try { 
	throw  new  Exception("This is an exception"); 
} catch(Throwable $e) { 
	echo $e->getMessage(); 


try { 
	$result = eval("2*'7'");
} catch(Throwable $e) { 
	echo $e->getMessage(); 

user defined

interface MyPackageThrowable extends Throwable {}
class MyPackageException extends Exception implements MyPackageThrowable {}
throw new MyPackageException();

what situations should throw an instance of a class extending Exception and what situations should throw an instance of a class extending Error? Error should be used to represent coding issues that require the attention of a programmer. Errorobjects thrown from the PHP engine fall into this category, as they generally result from coding errors such as providing a parameter of the wrong type to a function or a parse error in a file. Error objects should only be caught for logging, performing any necessary cleanup, and display an error message to the user.

Exception should be used for conditions that can be safely handled at runtime where another action can be taken and execution can continue.

  • Class Error: Arithmetic(x/0), Type(sum a string), Parse(eval with parse errors), Assertion
    Error is the base class of all the internal PHP errors. fatal errors are inherited from the Error class use Throwable class for custom exception catching and handling Virtually all errors in PHP 5.x that were fatal errors or recoverable fatal errors now throw instances of Error in PHP Error is the base class of all the internal PHP errors.

  • Class exception: Exception is the user exception base class.


require vs include if not found by require => fatal if not found by include => warning

Pdo: It is a lightweight PHP extension that uses consistence interface for accessing the database. Using PDO

Types of errors

Warnings: These are important errors. They will not result in ending the script. Notices: These errors are non-critical and trivial errors that come across while executing the script in PHP. Fatal errors: These are critical errors.

Php extensions PHP extensions are compiled libraries which enable specific functions to be used in your PHP code.

PEAR: PEAR is a framework and distribution system for reusable PHP components. It also provides a command line interface to install "packages" automatically. It behaves similarly to Composer but: the packages have to have a specific structure and pear installs packages globally. With composer pear is getting less used.

PECL is an online directory or repository for all known PHP extensions.

Nowdoc syntax: behaves the same way as single quotes except it is suited toward the use of multi-line strings.

$str = <<<'EOD'             // initialized by <<<
Example of string
spanning multiple lines
using nowdoc syntax.
$a does not parse.

Heredoc syntax: Heredoc syntax internally behaves the same way as double quotes except it is suited toward the use of multi-line strings

$str = <<<'EOD'             // initialized by <<<
Example of string
spanning multiple lines
using nowdoc syntax.
$a does not parse.
$str = "
Example of string
spanning multiple lines
using statement syntax.
$a are parsed.

generators enums php://stdout


The Standard PHP Library (SPL) is packaged with PHP and provides a collection of classes and interfaces. It is made up primarily of commonly needed datastructure classes (stack, queue, heap, and so on), and iterators which can traverse over these datastructures or your own classes which implement SPL interfaces.

  • Autoloader yes: the function used for autoloading => spl_autoload_register
  • File Handling yes: SplFileObject

  • DataTypes X : Native scalar type declarations support makes this extension mostly useless

  • Exceptions X : SPL provides a lot of exceptions. but its better if you name your own exceptions

  • Interfaces for Iterators

  • Data Structures: array has redesinged in php 7 and its more efficient than the most of ds but queue. Better use rudi ds in github

Miscellaneous Functions: class_implements, class_parents, classuses: better use reflection itertator... DONT


Iterators => there are better than generators (better readybillity, can be extended) Multiple Iterator yes

Security use composer

roave/security-advisories:dev-master ##check known-vulnerable packages

implement https security headers SQL XSS input validation csrf password hashing

History of PHP

PHP 5.3 (2009):

  • Lambda functions/closures: It helped to understand better allowin a set of commands in a callable anonymous function.
  • Namespaces: It helped to organize code.

PHP 5.4 (2012):

  • Traits
  • [] array
  • built-in server

Composer (2012)

PHP 5.5 5.6 (2013 - 2014):

  • ::class Scalar name resolution
  • finally for exceptions


  • performance (Zend engine rewritten)
  • uniform variable syntax -
 // Before
	$foo = new Foo();
	// After
	(new Foo())->bar();
  • null coalesce operator
// Before
$age = isset($data['age']) ? $data['age'] : 100;
// After
$age = $data['age'] ?? 100;
  • return type declarations and scalar type declarations

PHP 7.1 and 7.2

  • Error handling

in php5 we could catch exceptions but not errors => try {} catch (\Error $error){...}

we could work error handler but it's not good

\Exception and \Error implement \Throwable

  • Scalar type hinting

two modes => weak mode (php will try and for the argument into the type of the type hint) strict mode (will throw and error)

  • Return types
  • Nullable types
  • Void types
  • Private constants
  • Iterable: it's a type (\ArrayObject()) like array
  • Multi exception catch

Php 7.3

  • flexible heredoc
    • posibility of tab first line
    • no need to introduce new line at the end from:
<?php class foo {     
    public $bar = <<<EOT   


<?php class foo {     
    public $bar = <<<EOT       


$values = [<<<END   
END, 'd e f'];
  • Asign by reference on list
[$a, &$b, $c] = ['foo', 'bar', 'baz'];
  • trailing comma in function calls
$newArray = array_merge($one, $two, $three,)

but stil this gets an error

public function __construct(       
    array $options = [],   
) {  }

is_countable instead of

if (is_array($foo) || $foo instanceof Countable) { }

JSON Exception

use JsonException;  
try {     
  $json = json_encode($myArray, JSON_THROW_ON_ERROR);     
  return $json; 
} catch (JsonException $e) {     
  throw new \Exception('Not a valid json');

fpm_get_status array_key_first() y array_key_last()

Php 7.4

class A {       
  public string $name;            
  public Foo $foo; 


php.txt · Last modified: 2021/05/05 10:53 by superuser