Search code examples
phpinheritancephp4

php4 multi-level inheritance


Does this kind of inheritance work for php4?

class A {
    var $string;

    function A () {
        $this->string = "Hello";
    }
}

class B extends A {

    function B () {
        $this->string = "World";
    }
}

class C extends B {

    function C () {
        $this->string = "FooBar";
    }
}

$a = new A();
$b = new B();
$c = new C();
                    // OUTPUT:
echo $a->string;    //   "Hello"
echo $b->string;    //   "World"
echo $c->string;    //   "FooBar"

Solution

  • Firstly when your doing cross compatibility you should create a cross bread application that runs to the best standards on each platform.

    The way I would do this is sections of the the application that require PHP 5 specifics you would create a compatible directory and load the compatible file for PHP4

    for example:

    /application/classes/database/core.php
    /application/classes/database/util.php
    /application/classes/database/misc.php
    /compat/application/classes/database/core.php
    /compat/application/classes/database/util.php
    /compat/application/classes/database/misc.php
    

    is you can then do:

    function loadClass($path)
    {
        if (version_compare(PHP_VERSION, '5.0.0', '<'))
        {
             $path = "/compat/" . $path;
        }
    
        require_once $path;
    }
    
    loadClass("/application/classes/database/core.php");
    

    then as time goes on and nobody is using PHP 4 you can simply drop the compat directory and remove the check from loadClass.

    an alternative would be to register an autoloader, this way you can program using require_once within your application and reduce the need for an extra function to be palced through out your application.

    and answer your questions specifically about hte class stated above, this is perfectly cross compatible.

    If you stick with creating your application for PHP4 specifically you should take into consideration:

    • Do not use public / private modifiers for your class methods.
    • Always use the class name as the constructor instead of __construct.
    • When passing a class to a function, you should always pass by reference using the & symbol.
    • Do not use magic methods such as __tostring or __destruct.

    You should always create you application on a PHP4 system, and then test on the latest version of PHP5. (amend accordingly)