What's new in PHP 5.3?
PHP 6 is just around the corner, but for developers who just can't wait,
there's good news -- many of the features originally planned for PHP 6
have been back-ported to PHP 5.3, a final stable release of which is
due in the first half of this year.
This news might also be welcomed by those that wish to use some of
the new features, but whose hosting providers will not be upgrading to
version 6 for some time -- hosting providers have traditionally delayed
major version updates while acceptance testing is performed (read: the
stability has been proven elsewhere first). Many hosting companies will
probably delay upgrading their service offerings until version 6.1 to
be released. A minor upgrade from 5.2.x to 5.3, however, will be less
of a hurdle for most hosting companies.
This article introduces the new features, gives examples of where
they might be useful, and provides demo code to get you up and running
with the minimum of fuss. It doesn't cover topics such as installing
PHP 5.3 -- the latest development release of which is currently available. If you'd like to play along with the code in this article, you should install PHP 5.3, then download the code archive. An article on installing PHP 5.3 can be found on the Melbourne PHP Users Group web site.
Namespaces
Before the days of object oriented PHP, many application developers
made use of verbose function names in order to avoid namespace clashes.
Wordpress, for example, implements functions such as wp_update_post
and wp_create_user
. The wp_ prefix
denotes that the function pertains to the Wordpress application, and
reduces the chance of it clashing with any existing functions.
In an object oriented world, namespace clashes are less likely. Consider the following example code snippet, which is based on a fictional blogging application:
<?php
class User {
public function set( $attribute, $value ) { ... }
public function save() { ... }
}
$user = new User();
$user->set('fullname', 'Ben Balbo');
$user->save();
In this example, the save method will not clash with any other
method, as it is contained within the User class. There's still a
potential issue though: the User class might already be defined by some
other part of the system if, for example, the blogging application runs
within a content management system.
The solution to this issue is to use the new namespaces keyword. Taking the above code again, consider the following sample files:
<?php
namespace MyCompany::Blog;
class User {
public function set( $attribute, $value ) {
$this->$attribute = $value;
}
public function save() {
echo '<p>Blog user ' . $this->fullname . ' saved</p>';
}
}
<?php
$user = new MyCompany::Blog::User();
$user->set('fullname', 'Ben Balbo');
$user->save();
On the surface, the advantages offered by namespacing our function might not be immediately obvious -- after all, we've simply changed MyCompany_Blog_User
to MyCompany::Blog::User
. However, we can now create a User
class for the CMS using a different namespace:
<?php
namespace MyCompany::CMS;
class User {
public function set( $attribute, $value ) {
$this->$attribute = $value;
}
public function save() {
echo '<p>CMS user ' . $this->fullname . ' saved</p>';
}
}
MyCompany::Blog::User
and MyCompany::CMS::User
.The use
Keyword
Addressing classes using the full namespace still results in lengthy calls, and if you're using lots of classes from the MyCompany::Blog
namespace, you might not want to retype the whole path to the class every time. This is where the use
keyword comes in handy. Your application will most likely use a number of different classes at any given time. Say, for example, the user
creates a new post:
<?php
use MyCompany::Blog;
$user = new Blog::User();
$post = new Blog::Post();
$post->setUser( $user );
$post->setTitle( $title );
$post->setBody( $body );
$post->save();
The use
keyword is not restricted to defining namespaces in which to work. You can also use it to import single classes to your file, like so:
<?php
use MyCompany::Blog::User;
$user = new User();
Namespace Aliases
Earlier, I pointed out that one advantage of namespacing is the ability to define more than one class with the same name in different namespaces. There will obviously be instances where those two classes are utilized by the same script. We could just import the namespaces, however, we also have the option of importing just the classes. To do so, we can use namespace aliasing to identify each class, like so:
<?php
use MyCompany::Blog::User as BlogUser;
use MyCompany::CMS::User as CMSUser;
$bloguser = new BlogUser();
$bloguser->set('fullname', 'John Doe');
$bloguser->save();
$cmsuser = new CMSUser();
$cmsuser->set('fullname', 'John Doe');
$cmsuser->save();
Class Constants
Constants are now able to be defined at the class level! Note that class constants are available when you're importing namespaces, but you cannot import the constant itself. Here's an example of how we might use them:
<?php
namespace MyCompany;
class Blog {
const VERSION = '1.0.0';
}
<?php
echo '<p>Blog bersion ' . MyCompany::Blog::VERSION . '</p>';
use MyCompany::Blog;
echo '<p>Blog version ' . Blog::VERSION . '</p>';
use MyCompany::Blog::VERSION as Foo;
echo '<p>Blog version ' . Foo . '</p>';
This will result in the following output:
Blog bersion 1.0.0
Blog version 1.0.0
Blog version Foo
Namespaced Functions
The use of static class methods has deprecated the use of functions
in the object oriented world in which we now live. However, if you do
need to add a function to your package, it too will be subject to
namespacing!
Here's an example:
<?php
namespace bundle;
function foo() { echo '<p>This is the bundled foo</p>'; }
foo(); // This prints 'This is the bundled foo'
<?php
function foo() { echo '<p>This is the global foo</p>'; }
require( 'lib/bundle.class.php');
bundle::foo(); // This prints 'This is the bundled foo'
foo(); // This prints 'This is the global foo'
The Global Namespace
The global namespace is an important consideration when you're
dealing with functions. In the previous example, you'll notice that
there's no direct way of calling the global foo
function from within the bundle code.
The default method of resolving calls to functions is to use the
current namespace. If the function cannot be found, it will look for an
internal function by that name. It will not look in other namespaces
automatically.
To call the global foo
function from within the bundle namespace, we need to target the global namespace directly. We do this by using a double colon:
<?php
namespace bundle;
function foo() { echo '<p>This is the bundled foo</p>'; }
foo(); // This prints 'This is the bundled foo'
::foo(); // This prints 'This is the global foo'
Autoloading Namespaced Classes
If you're defining the magic __autoload
function to
include class definition files on demand, then you're probably making
use of a directory that includes all your class files. Before we could
use namespaces, this approach would suffice, as each class would be
required to have a unique name. Now, though, it's possible to have
multiple classes with the same name.
Luckily, the __autoload
function will be passed the fully namespaced reference to the class. So in the examples above, you might expect a call such as:
__autoload( 'MyCompany::Blog::User' );
You can now perform a string replace operation on this parameter to
convert the double colons to another character. The most obvious
substitute would be a directory separator character:
function __autoload( $classname ) {
$classname = strtolower( $classname );
$classname = str_replace( '::', DIRECTORY_SEPARATOR, $classname );
require_once( dirname( __FILE__ ) . '/' . $classname . '.class.php' );
}
./classes/mycompany/blog/user.class.php
.Late Static Binding
Late static binding provides the ability for a parent class to use a
static method that has been overridden in a child class. You might
imagine this would be the default behaviour, but consider the following
example:
<?php
class ParentClass {
static public function say( $str ) {
self::do_print( $str );
}
static public function do_print( $str ) {
echo "<p>Parent says $str</p>";
}
}
class ChildClass extends ParentClass {
static public function do_print( $str ) {
echo "<p>Child says $str</p>";
}
}
ChildClass::say( 'Hello' );
You would probably expect this to return "Child says Hello". While I
understand why you might expect this, you'll be disappointed to see it
return "Parent says Hello".
The reason for this is that references to self::
and __CLASS__
resolve to the class in which these references are used. PHP 5.3 now includes a static::
reference that resolves to the static class called at runtime:
static public function say( $str ) {
static::do_print( $str );
}
With the addition of the
static::
reference, the script will return the string "Child says Hello".
__callstatic
Until now, PHP has supported a number of magic methods in classes that you'll already be familiar with, such as __set
, __get
and __call
. PHP 5.3 introduces the __callstatic
method, which acts exactly like the call method, but it operates in a
static context. In other words, the method acts on unrecognized static
calls directly on the class.
The following example illustrates the concept:
<?php
class Factory {
static function GetDatabaseHandle() {
echo '<p>Returns a database handle</p>';
}
static function __callstatic( $methodname, $args ) {
echo '<p>Unknown static method <strong>' . $methodname . '</strong>' .
' called with parameters:</p>';
echo '<pre>' . print_r( $args, true ) . '</pre>';
}
}
Factory::GetDatabaseHandle();
Factory::CreateUser();
Factory::CreateBlogPost( 'Author', 'Post Title', 'Post Body' );
Variable Static Calls
When is a static member or method not static? When it's dynamically referenced, of course!
Once again, this is an enhancement that brings object functionalityto your classes. In addition to having variable variables and variable
method calls, you can now also have variable static calls. Taking the
factory class defined in the previous section, we could achieve the
same results by invoking the following code:
$methodname = 'CreateUser';
$classname::$methodname();
$methodname = 'CreateBlogPost';
$author = 'Author';
$posttitle = 'Post Title';
$postbody = 'Post Body';
$classname::$methodname( $author, $posttitle, $postbody );
You can create dynamic namespaces like so:
<?php
require_once( 'lib/autoload.php' );
$class = 'MyCompany::Blog::User';
$user = new $class();
$user->set('fullname', 'Ben Balbo');
$user->save();
No comments:
Post a Comment