Skip to main content

Examine PHP V5.3.0 features under the microscope

Stephen B. Morris, CTO, Omey Communications
Stephen Morris is the CTO of Omey Communications in Ireland. For the past 20 years, he has worked for some of the world's largest networking companies on a wide range of software projects, including J2EE/J2SE-based network management systems, billing applications, porting and developing SNMP entities, network device technologies, and GSM mobile networking applications. He is the author of Network Management, MIBs and MPLS: Principles, Design and Implementation (Prentice Hall PTR, 2003), as well as several articles on network management and other topics for InformIT and OnJava.com.

Summary:  As the popular PHP language continues to evolve, many new features enhance its object-oriented aspects. In this article, PHP V5.3 examples illustrate late static binding, namespace support, class method overloading, and variable parsing and heredoc support.

Date:  27 Oct 2009
Level:  Intermediate
Activity:  3686 views

Requirements for this article

Beyond a basic appreciation of PHP and HTML, there are no substantial requirements to follow this article. Anywhere I refer to PHP V5.3, I'm referring to V5.3.0.

Features reviewed

The following are the main PHP V5.3 features I look at in this article:

  • Late static binding
  • Namespaces
  • Class method overloading
  • Variable parsing and heredoc

However, before digging in, you need to set up PHP V5.3.


Setup

PHP has a reputation for being a bit difficult to set up. This is probably because a PHP installation sits on a Web server (Apache, for example) and often has a connection to an external database (MySQL, for example). Also, in a sense, PHP script code sits inside HTML code. In other words, PHP as a technology straddles a number of complex areas and disciplines. So, before you write a single line of PHP script code, you have to jump through a lot of hoops. I wish I could change all that, but many things to do with software technology are still quite difficult.

However, for those lucky readers using Apple Macs, the setup is about as simple as anyone could hope for:

  1. Get a copy of a PHP binary installer (http://www.entropy.ch/software/macosx/php/).
  2. Switch off Web Sharing in System Preferences.
  3. Locate the /etc/apache2/httpd.conf file.
  4. Comment out the following line in the httpd.conf file: LoadModule php5_module.
  5. Run the PHP V5.3 installer (you can build the source code if you prefer).
  6. Switch on Web Sharing in System Preferences.

I don't want this article to be just about installation, so if your platform is Microsoft® Windows® or Linux®, have a look at one of the many excellent PHP reference books available (see Resources for my recommendation).

To check that PHP is installed and that you're running the correct version, create a file called phpinfo1.php in the /Library/WebServer/Documents folder. Listing 1 illustrates the contents of the required script file. All the scripts in this article are available as part of the compressed (ZIP) file in the Download section, so you don't actually have to create any files if you want to follow along.


Listing 1. phpinfo1.php

<?php
phpinfo();
?>

After you place the script file in the /Library/WebServer/Documents folder, go to http://localhost/phpinfo1.php. You should see something like the excerpt illustrated in Figure 1. You might have to replace the word "localhost" in the URL with the IP address of your host machine.


Figure 1. PHP V5.3.0 is successfully installed
PHP V5.3 is successfully installed


Late static binding

PHP V5.3 extends the use of the static keyword. Static class methods and properties are accessible without the need for an instantiation of the class. This can be convenient for those situations where an object of the class is not available or not desirable. Listing 2 illustrates an example of late static binding.


Listing 2. Late static binding

<?php
class A {
    public static function who() {
        echo 'Calling who method from class '.__CLASS__;
    }
    public static function test() {
        static::who();
    }
}

class B extends A {
    public static function who() {
         echo 'Calling who method from class '.__CLASS__;
    }
}

B::test();
?>

The code in Listing 2 produces the following output:

Calling who method from class B

Improved object orientation

Any changes to PHP that enhance the object-oriented side of the language are to be encouraged because this leads to more solid design and more maintainable code. One minor quibble I have with the code in Listing 2 is the fact that the who() method code is duplicated in the base class (A) as well as the derived class (B). It would be nice if it was possible to not have to duplicate the code in class B, but it looks like the syntax of __CLASS__ in PHP V5.3.0 requires it. That is, __CLASS__ does not support late binding.

My use of __CLASS__ in Listing 2 is possibly a little contrived, but it does serve to illustrate a minor issue with PHP V5.3.0. Obviously, for the example in Listing 2, it's not a big deal, but the same wouldn't be true for a Web site with many thousands of lines of PHP code. Duplicate code generally means duplicate labor.

Prior to PHP V5.3.0, the method in class A might have been defined as self::who(). Unfortunately, this would have resulted in an invocation of the function from class A, rather than the one in the subclass class B. The use of the static:: keyword in PHP V5.3.0 fixes this by allowing you to reference at runtime the class method that was initially invoked. The latter is obviously the intention of the code in Listing 2.


Namespaces

PHP V5.3 provides namespaces to enhance the encapsulation strength of the language. Namespaces are quite common in modern languages, such as C# and XML. The main merit of namespaces is that they allow you to define isolated containers for code symbols (classes, functions, and constants), which sounds more difficult than it is. Listing 3 shows an example of using PHP namespaces to define local and global string constants.


Listing 3. PHP namespaces

<?php
namespace test;
define('ASTRING', 'Hello World!');
define('test\ASTRING', 'Hello World from my namespace!');

echo "<p>My string is: ";
echo ASTRING;
echo "</p>";

echo "<p>My string is ";
echo \ASTRING;
echo "</p>";
?>

The code in Listing 3 produces the following output:

My string is: Hello World from my namespace!
My string is: Hello World!

So, what's going on in this code? Well, the first define statement creates a string constant called ASTRING in the test namespace. When you then refer to the ASTRING string, the engine looks first in the local test namespace. This is why you see the locally defined string appearing first. Then, when you want to see the globally defined string, you simply use the syntax \ASTRING. These simple rules allow you to dip into any number of namespaces with no need to worry about name collisions.

The namespace facility allows for clearer code-level separation than before. This, in turn, helps to facilitate code integration in team environments. In other words, different teams can allocate their own namespaces and, when that convention is respected by all team members, the number of name clashes should be reduced to zero. This is, again, an object-oriented type of improvement in the PHP language that comes with V5.3.0.


Class method overloading

The term overloading in PHP is a little different from the usual object-oriented context. In the Java™ language or C#, an "overloaded" method is one that provides code for a range of different parameter lists. For example, if I have a method called draw(String str), an overloaded version can have the following form: draw(String str, int i). This use of the method symbol name is referred to as the method signature and, for the purposes of overloading, the return type is ignored.

In PHP, "overloading" is used to refer to dynamically created methods and properties. This is in effect dynamic code, and any such dynamic entities are processed by what are called magic methods. You can create these magic methods in a class for a variety of action types. Then, the overloading methods are invoked at the point in your code where you interact with undeclared or invisible properties or methods. This style of language overloading provides you with a substantial degree of flexibility.

This all sounds complicated, so look at an example to make it more concrete. Listing 4 illustrates using PHP overloading to invoke object and class methods.


Listing 4. PHP overloading

<?php
class OverloadedMethodTest {
    public function __call($name, $arguments) {
        // The value of $name is case sensitive.
        echo "Calling object method '$name' "
             . implode(', ', $arguments). "\n";
    }

    /**  As of PHP 5.3.0  */
    public static function __callStatic($name, $arguments) {
        // The value of $name is case sensitive.
        echo "Calling static method '$name' "
             . implode(', ', $arguments). "\n";
    }
}

$obj = new OverloadedMethodTest;
$obj->runOverloadedTest('in an object context');

OverloadedMethodTest::runOverloadedTest('in a static context');  // As of PHP 5.3.0
?>

The code in Listing 4 produces the following output:

Calling object method 'runOverloadedTest' in an object context
Calling static method 'runOverloadedTest' in a static context

Notice in Listing 4 the way the overloaded code has inferred the method names and parameters from the invocation code as follows:

$obj->runOverloadedTest('in an object context');

OverloadedMethodTest::runOverloadedTest('in a static context');  // As of PHP 5.3.0

This type of power does require a large degree of responsibility on the part of the programmer. The overloading facility provides for flexible code, but it also provides fertile ground for errors. So, overloading should be used with caution, along with a strong code-testing discipline.


Variable parsing and heredoc

One of the great strengths of PHP is string parsing. PHP has no limit on the size of a string, aside from the amount of host memory available. Listing 5 shows an example of the flexibility you get when using PHP parsing.


Listing 5. PHP parsing

<?php
$beverage = 'coffee';
// The following works; "'" is an invalid 
character for variable names echo "$beverage's taste is great"; // The following won't work; 's' is a valid
character for variable names but the echo "He drank a number of $beverages"; variable is "$beverage" echo "He drank some ${beverage}s"; // works echo "He drank some {$beverage}s"; // works ?>

The code in Listing 5 produces the following output:

coffee's taste is great
He drank a number of 
He drank some coffees
He drank some coffees

The code in Listing 5 isn't new to PHP V5.3.0. It is included simply to remind you about the string handling support and some of the parsing rules. However, PHP V5.3.0 adds enhanced heredoc syntax support. Listing 6 shows a simple example.


Listing 6. PHP V5.3.0 heredoc in action

<?php
echo >>>"FOOBAR"
Hello World!
FOOBAR;
?>

The code in Listing 6 produces the following spectacular output:

Hello World!

So, what's special about Listing 6? Well, the heredoc support in PHP V5.3.0 allows the use of double quotes. What benefit does this provide? Mainly, that the content inside the double quotes is not parsed, which provides you with more flexibility. Basically, this just adds a little more flexibility to the already-strong string support. The online references for PHP V5.3.0 include lots more material about this and other topics related to PHP V5.3.0.


Conclusion

PHP is an attractive technology. It facilitates a pick-and-mix model of Web-site development. You can add a database to your Web site and the PHP language has bindings necessary to achieve this with ease. You don't need heavyweight application servers or servlet technology. In other words, you get to control the environment with a minimum of investment — both financial and intellectual.

The PHP language continues to evolve, and I'm glad to see that many V5.3.0 improvements are effectively enhancements to the object-oriented aspects. This helps PHP compete with the more heavyweight (and more expensive) approaches to Web design.

In this article, I looked at late static binding, namespace support, class method overloading, and heredoc support. This is only a tiny part of the world of PHP V5.3.0. There are many other topics, such as migration to V5.3.0. Check out the Resources section for details on these and other areas.



Download

DescriptionNameSizeDownload method
Scripts for this articleos-php-v5.3ftrs-PHPScripts.zip2KBHTTP

Information about download methods


Resources

Learn

Get products and technologies

Discuss

About the author

Stephen Morris is the CTO of Omey Communications in Ireland. For the past 20 years, he has worked for some of the world's largest networking companies on a wide range of software projects, including J2EE/J2SE-based network management systems, billing applications, porting and developing SNMP entities, network device technologies, and GSM mobile networking applications. He is the author of Network Management, MIBs and MPLS: Principles, Design and Implementation (Prentice Hall PTR, 2003), as well as several articles on network management and other topics for InformIT and OnJava.com.

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source
ArticleID=433534
ArticleTitle=Examine PHP V5.3.0 features under the microscope
publish-date=10272009
author1-email=stephenbjm@yahoo.com
author1-email-cc=

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers