Dominique Stender Good software is only the beginning…

29Dec/090

Another reason to upgrade to PHP 5.3

php codeIn case you haven't found any specific reason to switch to PHP 5.3, I have one: Static properties.

Consider the following scenario: You have a group of classes, each responsible for returning a specific statistic. All these classes implement the same API, as given by a common abstract class.

Now, some of these statistics are publicly accessible, others require a certain access control permission to be set.

The logical approach would be to implement a static property to the abstract class, denying access by default. Those classes that are indeed public will overwrite the static property with the correct setting and become accessible.

The property is static to gain speed: There is no need to instantiate the class, if the access control is not satisfied.

Stripped down to the bare essentials the whole set of classes to outline the issue looks like this:

abstract class StatisticBase {
    public static $acl = '0';
} // end: class StatisticBase

class PublicStatistic extends StatisticBase {
    public static $acl = '1';
} // end: class StatisticBase

class AdminStatistic extends StatisticBase {
    // default value for $acl is fine
} // end: class AdminStatistic

AdminStatistic is an implemented class that is private, indicated by the $acl property being 0. PublicStatistic on the other hand is public, hence $acl is 1.

Now before instantiating a specific class we can check whether or not the access condition is satisfied:

if ($user->isAdmin == true || PublicStatistic::$acl == 1) {
    // retrieve admin statistic...
} // end: if

But naturally this is cumbersome as soon as you have more than a handful of statistics - you don't want to add another condition to your if-statement whenever you add a statistic. So the logical solution is a loop:

$statistics = array(
    'PublicStatistic',
    'AdminStatistic'
);

foreach ($statistics as $statClassName) {

    if ($user->acl == 1 || $statClassName::$acl == 0) {
        // retrieve current statistic...
    } // end: if
} // end: foreach

Here PHP 5.2 will fail with a fatal error.

You can't access static class properties by means of using a variable for the classname. PHP 5.3 can. There is no really elegant solution for this. (If you know one, post it in the comments!)

While I'm glad that PHP 5.3 has one more OOP feature covered, It leaves me with the feeling that we still have a long way to go until PHP fully supports object orientation.

Now, if Novel would please release a PHP 5.3 package for SLES 10 and SLES 11... thank you

Bookmark and Share

Related Posts:

Comments (0) Trackbacks (1)

Leave a comment