Sinjuice
Sinjuice

Reputation: 562

Constructor is not getting called

I have a strange problem with one of my classes.

The class is the next one

namespace Core;
class RequestHandler{
    protected $app;
    public function RequestHandler($app){
        echo "EEE";
        $this->app = $app;
    }
}

And the initialization is

$requestHandler = new Core\RequestHandler($app);

I don't know why it doesn't show anything, but if I change the constructor to __construct everything works fine.

I'm using php 5.6.20 and I know that it should execute the constructor by name too.

Upvotes: 3

Views: 441

Answers (1)

Justinas
Justinas

Reputation: 43451

Check example here:

<?php
namespace Foo;
class Bar {
    public function Bar() {
        // treated as constructor in PHP 5.3.0-5.3.2
        // treated as regular method as of PHP 5.3.3
    }
}
?>

Warning

Old style constructors are DEPRECATED in PHP 7.0, and will be removed in a future version. You should always use __construct() in new code.

So in 5.6.20 constructor by name is not deprecated.

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.

You may try to remove namespace, but I don't think it's good way to solve it.

Upvotes: 6

Related Questions