Dmitri Zaitsev
Dmitri Zaitsev

Reputation: 14056

Why is this method called without being asked to?

I came across this very strange behavior. The following code

class TestClass {
    function testClass() {
        echo "Don't show me!";
    }
}

$testing = new TestClass;

executes its method testClass without it being called! However, testClass won't run if renamed into anything else like testClass1. Is there any hidden 'PHP magic' behind this behaviour?

EDIT. At the end I see this question is trivial to ninjas grown up with PHP. As recent newcomer to PHP, I've learned to use __construct as constructor. With that "relic behaviour" carefully removed from modern tutorials. I am so glad people realized how terrible it was, changing class name and forgetting to change that of the constructor - what a nightmare!

Upvotes: 1

Views: 85

Answers (2)

user142162
user142162

Reputation:

Pre-PHP5, the __construct method was not used as the class constructor. Instead, a method with the same name as the class was used.

From the documentation:

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, and the class did not inherit one from a parent 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.

Creating a (empty) constructor (method named __construct) will stop the message from being echoed upon class initialization (only needed for < PHP 5.3.3 *):

class TestClass {
    function __construct() {

    }
    function testClass() {
        echo "Don't show me!";
    }
}

* As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

Upvotes: 6

OneOfOne
OneOfOne

Reputation: 99331

In older versions of PHP a method with the same name as the classname was considered the constructor.

Upvotes: 1

Related Questions