Shoe
Shoe

Reputation: 76300

How to prevent PHP from considering the functions, with the same name of a class, a constructor

Before PHP 5.3.3 the following

class Same {
    public function same() { echo 'Not good'; } 
}

$c = new Same();

will output Not good. From 5.3.3+ instead it will not output the string. That's because from PHP 5.3.3 functions with the same name of the class are not considered constructors. How do I force this behavior even with PHP 5.3.2 or before?

Upvotes: 1

Views: 245

Answers (3)

ajreal
ajreal

Reputation: 47331

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.

Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.

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.

docs:- http://php.net/manual/en/language.oop5.decon.php

So obvious solution is to declare a __constructors method (even is an empty one)

Upvotes: 2

TRD
TRD

Reputation: 1027

The construct method is named __construct(). Simply call your same()-method inside __construct() if u wish to have the same name.
According to http://php.net/construct php tries to reserve backwards compatibility. In my opinion the "same" name means writing the method name case-sensitive (as the class name). That should work too.

Upvotes: 0

pgl
pgl

Reputation: 8031

The easiest way is probably just to create an empty constructor:

class Same {
    public function same() { echo 'Not good'; } 

    public function __construct() { }
}

$c = new Same();

That won't echo "Not good" as the __construct() method overrides the "same name as class" method.

Upvotes: 4

Related Questions