3

I am unable to override a function in a child class at my local Ubuntu test LAMP server, but the very same code is resulting in the desired override when uploaded to a webserver.

Original class:

class HandsetDetection {
    function HandsetDetection() {
        //code I wish to replace
    }
}

My class:

class HandsetDetection_RespondHD extends HandsetDetection {
    function HandsetDetection() {
        //code I wish to use
    }
}

Constructors aren't involved.

The version of PHP in use on my local machine is PHP 5.3.3-1ubuntu9.5 with Suhosin-Patch (cli) (built: May 3 2011 00:48:48)

The version of PHP on the webserver where the override is successful is 5.2.17

Can you think why this may be?

David Oliver
  • 2,424
  • 1
  • 24
  • 37
  • Not unless you tell us what "is not working" means. – symcbean Jul 19 '11 at 12:00
  • 2
    as edorian said, it is treated as PHP4 constructor, which can't be overridden this way. – Yousf Jul 19 '11 at 12:04
  • "Constructors aren't involved." that's just wrong. Function `HandsetDetection::HandsetDetection` is the PHP 4 style constructor. See: Function Name = Class Name. – hakre Jul 19 '11 at 12:23
  • 1
    @David Oliver: You need to give the extending class another method and things should turn out as you need them, see [my answer below](http://stackoverflow.com/questions/6746749/unable-to-override-php-class-function/6747084#6747084). – hakre Jul 19 '11 at 12:27

2 Answers2

11

I would assume it has something to do with the fact that the class has the same name as the method.

It's a php4 style constructor.

As long as the class is not in a namespace that is still an issue.

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.


Example:

<?php


class A {

    function A() {
        echo "construct";
    }
}

class B extends A {

    function A() {
        echo "override";
    }

}

$x = new B();

This will output "construct"

now calling

$x->A();

will output "override".

edorian
  • 38,542
  • 15
  • 125
  • 143
2

Replace HandsetDetection() / prevent it from being called by giving the extending class a constructor method (Demo):

<?php

class A {

    function A() {
        echo "A() constructor\n";
    }
}

class B extends A {

    function __construct() {
        echo 'B() constructor', "\n";
    }

    function A() {
        echo "override\n";
    }

}

$x = new B();

Then things should turn out well. For an explanation about the background info, see @edorians answer with links to the manual etc.

hakre
  • 193,403
  • 52
  • 435
  • 836