Ryan Ryan - 3 months ago 8
PHP Question

Class instantiation causing functions within said class to be executed PHP

I have a registration class. The problem I'm facing is that the instantiation itself is somehow causing the functions within that class to be called.

I've tested this by adding an

error_log()
directly before and after the instantiation:
$register = new Register();
every time I receive another
error_log()
which I placed inside the functions of the class that I'm instantiating.

How can I solve this?

EDIT this is what an example may look like:




testclass.php

class Test {
public function test() {
error_log("Function test() was run.'");
}
}


test.php

require_once("testclass.php");

$test = new Test();

Answer

It's because your function, test() has the same name of the class Test so PHP is using it as the constructor and calling it when you instantiate it.

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
    }
}

As the docs say:

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.

Comments