If you're like me you remember the days of PHP3 and PHP4; you remember when PHP5 was released, and how it was touted to change to your life. It's still changing and there are some features of PHP 5.3 and new ones coming with PHP 5.4 that will improve your code readability and reusability. Let's look at some touted features such as closures, namespaces, and traits, as well as some features being discussed for future releases.
2. Hi! I am Jeff
Senior Developer at Texas A&M
Author of several magazine articles (php|architect)
Infrequent (lazy) blogger at carouth.com
Lover of progress, innovation, and improvement.
Developing with PHP since ~2003
2
3. About you?
New to PHP?
Using PHP 5.3?
Used PHP yesterday? this afternoon?
3
16. function get_closure($name) {
$person = new stdclass();
$person->name = $name;
return function() use($person) {
print "Hello, " . $person->name . "!";
};
}
$myhelloclosure = get_closure('Gernonimo');
$myhelloClosure();
// Output: "Hello, Geronimo!"
$myhelloclosure is said to “close over” the
$person variable which is within its defined scope.
16
33. define("LIBRARYDIR", __DIR__);
class Tamu_Cas_Adapter {
function auth() { }
}
function tamu_cas_create_client() {
return new Tamu_Http_Client();
}
namespace TamuCas;
use TamuHttpClient as HttpClient;
const LIBRARYDIR = __DIR__;
class Adapter {
function auth() { }
}
function create_client() {
return new HttpClient();
}
33
35. Conflict Resolution
namespace My;
function str_split($string, $split_len = 2) {
return "Nope. I don't like to split strings.";
}
$splitstr = str_split('The quick brown fox');
// $splitstr = "Nope. I don't like to split strings."
$splitstr = str_split('The quick brown fox');
// $splitstr = array('T', 'h', 'e', ..., 'o', 'x');
35
36. Class name shortening
class Zend_Application_Resource_Cachemanager
extends Zend_Application_Resource_ResourceAbstract
{
//...
}
namespace ZendApplicationResource;
class Cachemanager extends ResourceAbstract
{
//...
}
36
37. Readability by Namespace
require_once "Zend/Http/Client.php";
$client = new Zend_Http_Client();
use ZendHttp;
$client = new Client();
use ZendHttpClient as HttpClient;
$httpClient = new HttpClient();
37
41. Closures and $this
class HelloWorldPrinter
{
public function __construct($name) {
$this->_name = $name;
}
public function getPrinter() {
return function() {
return "Hello, " . $this->_name . "!";
};
}
}
$instance = new HelloWorldPrinter('BCSPHP');
$printer = $instance->getPrinter();
echo $printer();
41
42. Prior to PHP 5.4
Fatal error: Using $this when not in object context in /
Users/jcarouth/Documents/code-bcsphp-092011/
php54closurethis.php on line 14
PHP 5.4.0alpha3 (built Aug 5, 2011)
Hello, BCSPHP!
42
43. Short Array Syntax
Saving you a few keystrokes
and compute cycles when switching from JavaScript
43
47. $array = array(1, 2, 3);
$dereference = *$array;
Sorry, no pointers.
All the upset C++ wizards, go have some pizza.
47
48. class UserDataSource
{
public function getDataForJeff()
{
return [
'id' => 1,
'name' => 'Jeff Carouth',
'isAdmin' => true,
];
}
}
$jeff = $store->getDataForJeff();
if ($jeff['isAdmin'] === true) {
//give him access to all the things
}
PHP <= 5.3
if ($store->getDataForJeff()['isAdmin']) {
//shorter...but be mindful
}
48
PHP >= 5.4
51. Definition
Traits is a mechanism for code reuse in single
inheritance languages such as PHP. A Trait is
intended to reduce some limitations of single
inheritance by enabling a developer to reuse
sets of methods freely in several independent
classes living in different class hierarchies. The
semantics of the combination of Traits and
classes is defined in a way, which reduces
complexity and avoids the typical problems
associated with multiple inheritance and Mixins.
51
52. A bit much to
take in
The important bit is traits
allow developers like you to
increase code reuse and get
around limitations of single-
inheritance.
52
53. Show me the code!
trait Named {
function name() {
//function body
}
}
53
54. class SearchController {
public function findBook(Book $b) { }
private function log($message) {
error_log($message);
}
}
class AdminController {
public function grant(User $u, Privilege $p) { }
private function log($message) {
error_log($message);
}
}
54
55. trait Logging {
private function log($message) {
error_log($message);
}
}
class SearchController {
use Logging;
}
class AdminController {
use Logging;
}
55
56. namespace TamuTimesModels;
class Story {
public function setDataStore($store) {
$this->_ds = $store;
}
public function getDataStore() {
return $this->_ds;
}
}
class User {
public function setDataStore($store) {
$this->_ds = $store;
}
public function getDataStore() {
return $this->_ds;
}
}
56
57. namespace TamuDmcApp;
trait DataStore {
public function setDataStore($store) {
$this->_ds = $store;
}
public function getDataStore() {
return $this->_ds;
}
}
namespace TamuTimesModels;
use TamuDmcAppDataStore;
class Story {
use DataStore;
}
class User {
use DataStore;
}
57
58. namespace BCSPHP;
trait MessageBroadcast {
public function sendMessage() { }
abstract private function _formatMessage();
}
class MeetingNotification {
use MessageBroadcast;
private function _formatMessage() {
return "Notice: BCSPHP Meeting " . $this->_date;
}
}
58
59. Traits are “just compiler
assisted copy and paste.”
- Stefan Marr, PHP Internals Mailing List, Nov 2010
59
66. Resources
Enygma’s PHP 5.3 example code
http://bit.ly/q9Eu36
Elazar’s benchmarks of SPL features in PHP 5.3
http://bit.ly/nKsbvQ
PHP documentation on the built-in web server
http://bit.ly/rc26l0
66
Notes de l'éditeur
\n
\n
\n
PHP 5.3.0 released June 30, 2009.\nBugfixes and security patches in 5.3.1-5.3.6 (11/2009-3/2011)\n5.3.7 released on Aug. 18, 2011. focused on improving stability\n5.3.8 released shortly after (Aug 23) to fix two issues introduced in .7\n
Listed in an ascending level of interesting-ness.\nMagic Constants: LINE, FILE, DIR, FUNCTION, CLASS, METHOD, NAMESPACE\nStandard PHP Library\n
\n
__DIR__ does not include a trailing space\n
Sometimes marginal differences in throughput (execs/sec), but memory consumption is generally lower with respect to dataset size (num elements)\n
\n
\n
\n
\n
\n
\n
\n
This isn&#x2019;t a terribly intriguing use case, so let&#x2019;s look at a more practical example.\n
\n
\n
\n
\n
\n
\n
\n
\n
Cannot do use(new Obj() as $s) :-(\n
\n
\n
\n
\n
\n
Just get over it. Embrace the backslash.\n
Organize OO code into self-contained units.\nEver heard of the global namespace pollution issue?\nPEAR naming convention\nImports and aliases.\n
\n
\n
\n
\n
\n
\n
\n
\n
Before 5.4 you cannot refer to the object instance that created the closure.\nEXAMPLE\n