php uzanan ancak yeni bir kurucu ile mümkündür ...?

2 Cevap

Ben bir sınıf vardır:

class test {
    function __construct() {
        print 'hello';
    }
    function func_one() {
        print 'world';
    }
}

ne yapmak istersiniz bir çeşit deney sınıfını genişleten bir sınıf var. Ben sınıf test sınıf çalışabiliyor ne olursa olsun fonksiyonu çalıştırmak edebilmek gerekiyor, çünkü 'tür' demek, ama ben onu sormak sürece yapıyı çalıştırmak değil. Ben yapı geçersiz istemiyorum. Herkes nasıl bunu başarmak için herhangi bir fikir var?

2 Cevap

Ne yapıyı geçersiz kılma ile yanlış?

class foo extends test {
   function __construct() { }
}

$bar = new foo(); // Nothing
$bar->func_one(); // prints 'world'

Eğer kök sınıf yapıcısı idam edeceğini alt sınıflar bir "preConstructor" yöntemini tanımlamak ve yapıcı kod idam gerektiğini belirlemek için bir boolean bayrak kullanabilirsiniz.

Şöyle:

class test
{
    protected $executeConstructor;

    public function __construct()
    {
        $this->executeConstructor = true;
        if (method_exists($this, "preConstruct"))
        {
            $this->preConstruct();
        }

        if ($this->executeConstructor == true)
        {
            // regular constructor code
        }
    }
}

public function subTest extends test
{
    public function preConstruct()
    {
        $this->executeConstructor = false;
    }
}