PHP 5.6 was released in August 2014, bringing significant improvements and new features that make PHP development more enjoyable and powerful. At ZIRA Software, we've been using PHP 5.6 in production since release, and these features have improved our code quality and developer productivity.
What's New in PHP 5.6
PHP 5.6 includes:
- Variadic functions using
... - Argument unpacking
- Constant scalar expressions
- Constant array/string dereferencing
- Namespace function/constant imports
- Internal operator overloading
- Large file uploads (>2GB)
- Better debugging with
phpdbg
Variadic Functions
Accept unlimited arguments with ... operator:
Before PHP 5.6:
function sum() {
$args = func_get_args();
return array_sum($args);
}
echo sum(1, 2, 3, 4, 5); // 15
With PHP 5.6:
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4, 5); // 15
Type hints with variadic:
function concatenate(string $separator, string ...$strings) {
return implode($separator, $strings);
}
echo concatenate(' - ', 'Laravel', 'PHP', 'MySQL');
// Output: Laravel - PHP - MySQL
Real-world example:
class Logger {
public function log($level, $message, ...$context) {
$contextStr = '';
if (!empty($context)) {
$contextStr = json_encode($context);
}
echo "[{$level}] {$message} {$contextStr}\n";
}
}
$logger = new Logger;
$logger->log('ERROR', 'User not found', ['user_id' => 123]);
// [ERROR] User not found {"user_id":123}
Argument Unpacking
Unpack arrays into function arguments:
function add($a, $b, $c) {
return $a + $b + $c;
}
$numbers = [1, 2, 3];
echo add(...$numbers); // 6
Combining with regular arguments:
function query($table, $where, ...$columns) {
echo "SELECT " . implode(', ', $columns) . " FROM {$table} WHERE {$where}";
}
$columns = ['name', 'email', 'created_at'];
query('users', 'active = 1', ...$columns);
// SELECT name, email, created_at FROM users WHERE active = 1
Practical use case:
class EventDispatcher {
public function fire($event, ...$args) {
$listeners = $this->getListeners($event);
foreach ($listeners as $listener) {
call_user_func($listener, ...$args);
}
}
}
$dispatcher = new EventDispatcher;
$dispatcher->fire('user.registered', $user, $timestamp, $ip);
Constant Scalar Expressions
Define constants using expressions:
Before PHP 5.6:
const THREE = 3;
const FIVE = 5;
// const EIGHT = THREE + FIVE; // Not allowed!
With PHP 5.6:
const THREE = 3;
const FIVE = 5;
const EIGHT = THREE + FIVE; // Now allowed!
const ALLOWED_EXTENSIONS = ['jpg', 'png', 'gif'];
const MAX_SIZE = 10 * 1024 * 1024; // 10MB
In class constants:
class FileUploader {
const MAX_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif'];
const AVATAR_WIDTH = 200;
const AVATAR_HEIGHT = 200;
const AVATAR_DIMENSIONS = self::AVATAR_WIDTH . 'x' . self::AVATAR_HEIGHT;
}
Configuration example:
class Config {
const ENV = 'production';
const DEBUG = self::ENV === 'development';
const BASE_URL = 'https://example.com';
const API_URL = self::BASE_URL . '/api/v1';
const CACHE_LIFETIME = 60 * 60 * 24; // 24 hours in seconds
}
Namespace Function and Constant Imports
Import functions and constants from namespaces:
Before PHP 5.6:
use Some\Namespace\ClassName;
// But you couldn't import functions or constants
With PHP 5.6:
namespace App\Controllers;
use App\Models\User;
use function App\Helpers\encrypt;
use function App\Helpers\decrypt;
use const App\Config\MAX_UPLOAD_SIZE;
class UserController {
public function store() {
$password = encrypt(Input::get('password'));
if (Input::file('avatar')->getSize() > MAX_UPLOAD_SIZE) {
return 'File too large';
}
}
}
Multiple imports:
use function App\Helpers\{encrypt, decrypt, hash_password};
use const App\Config\{DB_HOST, DB_NAME, DB_USER};
$encrypted = encrypt($data);
$connection = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER);
Constant and Variable Dereferencing
Access array elements and string characters from constants:
const FRUITS = ['apple', 'banana', 'orange'];
echo FRUITS[1]; // banana
const VERSION = '5.6.0';
echo VERSION[0]; // 5
Method chaining:
class Config {
const SETTINGS = [
'db' => [
'host' => 'localhost',
'port' => 3306
]
];
}
echo Config::SETTINGS['db']['host']; // localhost
Practical example:
class Response {
const HTTP_CODES = [
200 => 'OK',
404 => 'Not Found',
500 => 'Internal Server Error'
];
public static function message($code) {
return self::HTTP_CODES[$code] ?? 'Unknown';
}
}
echo Response::message(404); // Not Found
Exponential Operator
New ** operator for exponentiation:
// Before
echo pow(2, 8); // 256
// With PHP 5.6
echo 2 ** 8; // 256
// Assignment operator
$num = 2;
$num **= 3;
echo $num; // 8
Practical use:
class FileSize {
public static function megabytes($size) {
return $size * (1024 ** 2);
}
public static function gigabytes($size) {
return $size * (1024 ** 3);
}
}
echo FileSize::megabytes(10); // 10485760
Large File Uploads
Support for files larger than 2GB:
// Now works with files > 2GB
$file = $_FILES['large_file'];
if ($file['size'] > 2 * 1024 ** 3) { // 2GB
echo "File is larger than 2GB: " . $file['size'] . " bytes";
}
Configuration:
; php.ini
upload_max_filesize = 4G
post_max_size = 4G
Default Character Encoding
Set default character encoding:
// php.ini
default_charset = "UTF-8"
// Now you don't need to specify charset everywhere
header('Content-Type: text/html'); // Automatically adds charset=UTF-8
php://input is Reusable
Read request body multiple times:
// Read once
$data = file_get_contents('php://input');
// Read again - now possible in PHP 5.6!
$dataCopy = file_get_contents('php://input');
Practical application:
class ApiController {
public function store() {
// Log request
$requestBody = file_get_contents('php://input');
Log::info('API Request', ['body' => $requestBody]);
// Process request (read again)
$data = json_decode(file_get_contents('php://input'), true);
// Handle data
return $this->process($data);
}
}
GMP Objects Support Operator Overloading
$a = gmp_init('1234567890');
$b = gmp_init('9876543210');
// Old way
$result = gmp_add($a, $b);
// PHP 5.6 way - operator overloading
$result = $a + $b;
$result = $a * $b;
$result = $a - $b;
Better Debugging with phpdbg
PHP 5.6 includes phpdbg, an interactive debugger:
# Start debugger
phpdbg script.php
# Set breakpoint
phpdbg> break main
phpdbg> run
# Step through code
phpdbg> step
phpdbg> continue
# Inspect variables
phpdbg> print $variable
Performance Improvements
PHP 5.6 includes numerous performance improvements:
Benchmark results (from our production servers):
- 10-15% faster than PHP 5.5
- Reduced memory usage
- Better opcode cache with OPcache
// Example: String concatenation is faster
$str = '';
for ($i = 0; $i < 10000; $i++) {
$str .= 'test';
}
// ~15% faster in PHP 5.6
Migrating to PHP 5.6
Breaking Changes
- JSON decoding is stricter:
// This may fail in PHP 5.6 if JSON is malformed
$data = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Invalid JSON');
}
- GMP resources are now objects:
// Old code using is_resource() will break
if (is_resource($gmp)) { } // False in PHP 5.6
// Use this instead
if ($gmp instanceof GMP) { }
Migration Checklist
- [ ] Test with
E_DEPRECATEDenabled - [ ] Update GMP resource checks
- [ ] Verify JSON decoding error handling
- [ ] Test large file uploads
- [ ] Update character encoding settings
- [ ] Review third-party library compatibility
Real-World Examples
Building a Flexible Query Builder
class QueryBuilder {
protected $table;
protected $wheres = [];
public function where($column, $operator, ...$values) {
if (count($values) === 0) {
$values = [$operator];
$operator = '=';
}
$this->wheres[] = [$column, $operator, ...$values];
return $this;
}
public function get(...$columns) {
$cols = empty($columns) ? '*' : implode(', ', $columns);
return "SELECT {$cols} FROM {$this->table}";
}
}
$query = new QueryBuilder('users');
$sql = $query->where('active', 1)
->where('role', 'admin')
->get('name', 'email', 'created_at');
Configuration Management
class Config {
const ENV = 'production';
const DEBUG = self::ENV !== 'production';
const DB_CONNECTION = 'mysql';
const DB_HOST = 'localhost';
const DB_PORT = 3306;
const DB_NAME = 'myapp';
const CACHE_DRIVER = 'redis';
const CACHE_TTL = 60 * 60; // 1 hour
const ALLOWED_IMAGE_TYPES = ['jpg', 'png', 'gif', 'webp'];
const MAX_IMAGE_SIZE = 5 * 1024 ** 2; // 5MB
}
if (Config::DEBUG) {
error_reporting(E_ALL);
}
Conclusion
PHP 5.6 brings meaningful improvements that make PHP code cleaner and more maintainable. At ZIRA Software, we recommend upgrading to PHP 5.6 for all new projects and planning migrations for existing applications.
The variadic functions, argument unpacking, and constant expressions eliminate common boilerplate code. Combined with performance improvements, PHP 5.6 represents a solid evolution of the language.
Need help upgrading your PHP applications? Contact ZIRA Software to discuss migration strategies, performance optimization, and modern PHP development practices.