PHP 5: the release that made PHP object-oriented

Introduction

PHP 5 (2004, Zend Engine 2) is the release modern PHP descends from: objects finally behave (handles, not copies), errors become catchable, and databases get one sane API. PHP 4 code mostly runs, but the way serious code is written changes completely.

Author: Arthur Isaev

Real object orientation

Visibility (public, protected, private), interfaces, abstract classes, instanceof, static members, and autoloading: the full OOP toolkit our OOP articles build on. (Namespaces below need 5.3+; the rest is 5.0.)

<?php namespace Aredel\Demo; interface Renderable { public function render(); } class ArticlePage implements Renderable { public function render() { return 'article'; } }

Exceptions instead of die()

try / catch with an Exception hierarchy replaces die() and PEAR-style error returns: failures carry a stack trace and a type you can catch selectively.

<?php namespace Aredel\Demo; try { $page = loadPage($_GET['id']); } catch (MissingPageException $e) { echo 'Not found'; }

One API for every database

PDO unifies MySQL, PostgreSQL, SQLite and others behind one interface, with prepared statements as the default: values go as bound parameters, so quoting bugs and SQL injection shrink to a fraction of the old mysql_* code.

Same release, smaller tools: SimpleXML for reading XML without a parser manual, and the SPL (autoloading, iterators, countable objects).

What 5.3 and 5.4 added

PHP 5.3: namespaces, closures, late static binding, and the short ternary (?:).

PHP 5.4: traits (see traits in PHP), short array syntax ([]), and a built-in web server for development.

Next: PHP 7 — same language, roughly twice as fast, with scalar types.

Автор статьи: Андрей Олегович