Raffael Raffael - 1 year ago 80
PHP Question

cannot define constructor as protected or private! why?

--- A.php ----
require_once 'B.php';

class A
public function __constructor($x){...}

public function foo()
$b = B::getInstance();

--- B.php ----
require_once 'A.php';

class B extends A
protected static $_instance = null;

protected function __construct(){}

public static function getInstance()

PHP just stops interpreting the code as soon as it reaches line

protected function __construct(){}

and outputs everything before and nothing that would have been sent to the browser afterwards.

And as soon as I just take that line out, by changing it to

// protected function __construct(){}

everything works fine!?

I don't get that.

Any ideas?

Answer Source

I've just created a simple test-file to confirm whether this happens on my machine too, and I think I've found the answer. Take the following code:

error_reporting( E_ALL | E_STRICT );
class Foo {
    public function __construct( ) {

class Bar extends Foo {
    protected function __construct( ) {

When trying to execute that code, I get a fatal error: "PHP Fatal error: Access level to Bar::__construct() must be public (as in class Foo) in /home/berry/foo.php on line 12." That means you can't change the access level in a child class, if the parent has already defined the access level, which actually makes a lot of sense: PHP wouldn't know which constructor to call, I guess.

As a side note: by looking at your code, B extends A, and A uses B. Why exactly is that so, it seems like a strange construction to me? I'm guessing you actually want is composition, not inheritance.