OOP in PHP 4 and 8

Deprecation of class name constructors means that you no longer can write OOP code that works both in PHP 4 and PHP 8 without some hackery. This works however:

<?php

class WorksIn4And8
{
    var $int;

    // Regular method in PHP 4
    // Constructor in 5-8
    function __construct($int)
    {
        error_log('__construct()');
        $this->int = $int;
    }

    // Constructor in PHP 4
    // Constructor overridden by __construct in 5-7
    // Regular method in PHP 8
    function WorksIn4And8($int)
    {
        error_log('WorksIn4And8()');
        $this->__construct($int);
    }

    function getInt()
    {
        return $this->int;
    }
}

$obj = new WorksIn4And8(48);

var_dump($obj->getInt());

Comments

Comments powered by Disqus