9

他の多くのクラスによって拡張された親クラスがあり、親クラスのコンストラクターが常に実行されるようにしたい場合、コンストラクターを宣言するのは悪い考えfinalですか?

私はこのようなことを考えていました:

class ParentClass {

    public final function __construct() {

        //parent class initialization...

        $this->construct();

    }

    protected function init() {

        echo 'constructing<br>';

    }

}

class ChildClass extends ParentClass {

    protected function init() {

        //child class initialization

        echo 'constructing child<br>';

    }

}

そうすれば、子クラスは一種のコンストラクターを持つことができ、親クラスのコンストラクターは常に実行されます。これは悪い習慣ですか?

4

3 に答える 3

10

を宣言するfinal __constructと、クラスを拡張する誰もが同じ名前のメソッドを実装できないことが保証されます。表面的には、これは他の誰もこのクラスのサブクラスのコンストラクターを宣言できないことを意味するように見えますが、これは正しくありませんClassName()。コンストラクタ。つまり、コンストラクターを final として宣言しても、PHP では何も得られません。

于 2010-01-03T01:54:59.493 に答える
6

PHP 5.3.3 の時点で、私はこれを 5.6 と 7.0 でテストしました。クラスの__constructメソッドを宣言するfinalと、コンストラクターをオーバーライドする子クラス__constructが PHP 4 スタイルまたは PHP 4 スタイルを使用するのを防ぐことができますClassName()(PHP 4 スタイルは PHP の時点で非推奨であることに注意してください)。 7)。コンストラクターを宣言する子クラスを防止すると、親コンストラクターが常に呼び出されるようになります。もちろん、これにより、子クラスが独自のコンストラクターロジックを実装することはできなくなります。これには間違いなく実用的な使用例がありますが、一般的には推奨しません。

いくつかの例:

__constructfinal を宣言せずに

class ParentClassWithoutFinal {
    private $value = "default";

    public function __construct() {
        $this->value = static::class;
    }

    function __toString() {
        return $this->value;
    }
}

class ChildClassA extends ParentClassWithoutFinal {
    public function __construct() {
        // Missing parent::__construct();
    }
}

echo (new ChildClassA()); // ouput: default

ファイナル付き__construct

class ParentClassWithFinal extends ParentClassWithoutFinal {
    public final function __construct() {
        parent::__construct();
    }
}

class ChildClassB extends ParentClassWithFinal {
}

echo (new ChildClassB()); // output: ChildClassB

__construct子クラスで 宣言しようとしています

class ChildClassC extends ParentClassWithFinal {
    public function __construct() {
    }
}

// Fatal error: Cannot override final method ParentClassWithFinal::__construct()

ClassName()子クラスでコンストラクター を宣言しようとしています

class ChildClassD extends ParentClassWithFinal {
    public function ChildClassD() {
    }
}

// Fatal error: Cannot override final ParentClassWithFinal::__construct() with ChildClassD::ChildClassD()
// Also in PHP 7: Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; ChildClassD has a deprecated constructor
于 2016-09-29T01:12:15.960 に答える
-1

コンストラクターをファイナライズした後は、変数を初期化関数に渡すことはできません。クラスのユーザーは、子クラスの設定としてグローバルを使用する必要があります。

Zend Framework では、オーバーライド可能な init() を使用するのが一般的ですが、そこでコンストラクターをファイナライズするのを見たことがありません。

于 2010-01-03T01:28:21.787 に答える